2016-03-26 27 views
3

這可能嗎?我希望能夠根據用戶輸入整理一個表體,所以我只是把這個小測試放在一起看看它是否可以工作,但是它加載了所有的虛體,表體的前面和外面在DOM,即使我在我的html中適當地嵌套它。所以我的問題是這樣的: 1)這是什麼行爲?和 2)我可以達到我想要的方式嗎?在表格中嵌套指令

* simple fiddle

HTML:

<div ng-app="myApp" ng-controller="myController"> 
<table class="table"> 
<thead> 
    <tr> 
    <th>Month</th> 
    <th>Savings</th> 
    </tr> 
</thead> 
<my-directive></my-directive><!-- this should be the tbody --> 
<tfoot> 
    <tr> 
    <td>Sum</td> 
    <td>$180</td> 
    </tr> 
</tfoot> 
</table> 
</div> 

JS:

var app = angular.module("myApp", []); 

app.directive("myDirective", function() { 
    return { 
     restrict: 'E', 
     template: '<tbody><tr><td>January</td><td>$100</td></tr><tr><td>February</td><td>$80</td></tr></tbody>', 

    }; 
}); 

回答

2

您正在渲染<my-directive></my-directive>元素,這是搞亂表格的佈局中的標記。

相反,你的指令改變爲基於屬性的指令,並將其放置在<tbody>元素,更換內容..

模板

</thead> 
<tbody my-directive></tbody><!-- this should be the tbody --> 
<tfoot> 

指令

return { 
    restrict: 'A', 
    template: '<tr><td>January</td><td>$100</td></tr><tr><td>February</td><td>$80</td></tr>' 
}; 

見工作fiddle

+0

@spb看到更新和工作小提琴。它會因替換而炸燬,因爲它無法正確定義根元素。替換不是正確的解決方案。相反,只需更換tbody的內部內容即可。 –

+0

並炸掉它。哈哈。感謝修復。你最好。 – spb

+0

是的,是的,我一開始就把它炸掉了:)。沒問題,樂意幫忙! –