AngularJS – 将元素附加到指令内的每个ng-repeat迭代

前端之家收集整理的这篇文章主要介绍了AngularJS – 将元素附加到指令内的每个ng-repeat迭代前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在< tr>里面使用了ng-repeat.元素和指令.

HTML:

  1. <tbody>
  2. <tr ng-repeat="row in rows" create-table>
  3. <td nowrap ng-repeat="value in row | reduceString>{{value}}</td>
  4. </tr>
  5. </tbody>

指示:

  1. app.directive('createTable',function () {
  2. return {
  3.  
  4. link: function (scope,element,attrs) {
  5. var contentTr = scope.$eval('"<tr ng-show=&quot;false&quot;><td>test</td></tr>"');
  6. $(contentTr).insertBefore(element);
  7. }
  8. }
  9. }
  10. );

虽然我可以添加一个新的< tr>每次迭代的元素,我都无法在将角色代码添加到DOM后执行(例如< tr>中的ng-show).我错过了一些明显的东西吗

您没有在您的孩子内部获得Angular绑定的原因是因为您缺少 compiling.当链接函数运行时,元素已经被编译,因此,Angular增强了.您所要做的就是手动编译您的内容.首先,不要评估您的模板,否则您将丢失绑定提示.
  1. app.directive('createTable',function ($compile) {
  2. return {
  3. link: function (scope,attrs) {
  4. var contentTr = angular.element('<tr ng-show=&quot;false&quot;><td>test</td></tr>');
  5. contentTr.insertBefore(element);
  6. $compile(contentTr)(scope);
  7. }
  8. }
  9. });

另一个提示:你永远不会将你的元素包含在jQuery($)中.如果您的页面中有jQuery,则所有Angular元素都已经是jQuery增强元素.

最后,解决所需问题的正确方法是使用指令编译函数(读取‘Compilation process,and directive matching’ and ‘Compile function’)在编译之前修改元素.

作为最后的努力,阅读整个Directive guide,这是一个宝贵的资源.

猜你在找的Angularjs相关文章