2013-03-31 32 views
3

我在<tr>元素中使用ng-repeat和指令。AngularJS - 在指令中的每個ng-repeat迭代中追加元素

HTML:

<tbody> 
    <tr ng-repeat="row in rows" create-table> 
    <td nowrap ng-repeat="value in row | reduceString>{{value}}</td> 
    </tr> 
</tbody> 

指令:

app.directive('createTable', function() { 
     return { 

      link: function (scope, element, attrs) { 
       var contentTr = scope.$eval('"<tr ng-show=&quot;false&quot;><td>test</td></tr>"'); 
       $(contentTr).insertBefore(element); 
      } 
     } 
    } 
); 

雖然我可以追加一個新<tr>元素每次迭代中,我沒能得到執行的角度代碼它被添加到後DOM(例如<tr>內的ng-show)。我錯過了明顯的東西嗎?

回答

12

你的孩子沒有得到Angular綁定的原因是因爲你缺少compiling。當鏈接函數運行時,該元素已經被編譯,因此Angular增加了。您只需要手動輸入$compile您的內容即可。首先,不要評估你的模板,否則你會失去你的綁定提示。

app.directive('createTable', function ($compile) { 
    return { 
    link: function (scope, element, attrs) { 
     var contentTr = angular.element('<tr ng-show=&quot;false&quot;><td>test</td></tr>'); 
     contentTr.insertBefore(element); 
     $compile(contentTr)(scope); 
    } 
    } 
}); 

另一個祕訣:你從來沒有附上元素的jQuery($)。如果你的頁面中有jQuery,所有的Angular元素都已經是一個jQuery增強元素。

最後,解決您需要的正確方法是使用指令compile函數(讀取'Compilation process, and directive matching' and 'Compile function')在其編譯之前修改元素。

作爲最後的努力,閱讀整個Directive guide,這是一個寶貴的資源。

相關問題