首页 > 解决方案 > 为什么 $compile 在 ng-repeat 中创建多个元素?

问题描述

为什么 $compile 在 ng-repeat 中创建多个元素?

HTML:

<li ng-repeat="action in actions" set-on-click function="{{action.function}}"><i class="{{action.class}}" aria-hidden="true"></i>{{action.text}}</li>

指示:

directive('setOnClick', ['$compile', function ($compile) {
    return {
        restrict: "A",
        link: function(scope, elm, attrs, ctrl)
        {
          console.log(attrs.function);  
          elm.attr("ng-click", attrs.function);
          elm.removeAttr("set-on-click");
          $compile(elm)(scope);
        }
      };
}]);

$scope.actions我从有 3 条记录的数据库中获取价值。我必须使用指令才能绑定ng-click到我从数据库中获取的函数。而不是得到 3 li 项目,我得到 9。每个 li 都重复三次。有人可以解释为什么吗?有没有办法阻止这种重复?

标签: angularjsangularjs-directive

解决方案


推荐阅读