3

我在<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);
            }
        }
    }
);

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

4

1 回答 1

12

您没有在孩子体内获得 Angular 绑定的原因是您缺乏编译。当链接函数运行时,元素已经被编译,因此,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函数(阅读“编译过程和指令匹配”和“编译函数”)在编译之前修改元素。

作为最后的努力,阅读整个指令指南,这是一个宝贵的资源。

于 2013-03-31T15:17:35.717 回答