【问题标题】:AngularJS - Append element to each ng-repeat iteration inside a directiveAngularJS - 将元素附加到指令内的每个 ng-repeat 迭代
【发布时间】:2013-03-31 23:17:35
【问题描述】:

我在 <tr> 元素中使用 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);
            }
        }
    }
);

虽然我可以在每次迭代中附加一个新的&lt;tr&gt; 元素,但在将其添加到 DOM 后,我无法执行 Angular 代码(例如 &lt;tr&gt; 中的 ng-show)。我错过了一些明显的东西吗?

【问题讨论】:

    标签: angularjs directive ng-repeat


    【解决方案1】:

    你没有在你的孩子体内获得 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,这是一个宝贵的资源。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      相关资源
      最近更新 更多