小编典典

angularjs将属性中新创建的数组传递给指令

angularjs

我创建了这个小提琴来显示我的问题…

http://jsfiddle.net/dQDtw/

我正在将一个新创建的数组传递给指令,并且一切正常。但是,在控制台窗口中出现错误,指示:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!

对我需要按摩以清洁它的任何想法吗?我希望能够重用指令,而无需更新控制器。

这是HTML

<body ng-app="myApp">
    <test-dir fam-people='[1,4,6]'> </test-dir>
    <test-dir fam-people='[2,1,0]'> </test-dir>
</body>

这是JS。

var myApp = angular.module(’myApp’,[]);

myApp.directive('testDir', function() {
            return { restrict: 'E'
                   , scope: { famPeople: '=famPeople' }
                   , template: "<ol> <li ng-repeat='p in famPeople'> {{p}}"
                   };
    });

阅读 230

收藏
2020-07-04

共1个答案

小编典典

该错误是因为您的指令无法将数组解释为数组,请尝试以下操作:

<body ng-app="myApp" ng-controller="ctrl1">
    <test-dir fam-people='people'> </test-dir>

</body>



var myApp = angular.module('myApp', []);

myApp.directive('testDir', function() {
                return { restrict: 'E'
                       , scope: { famPeople: '=' }
                       , template: "<ol> <li ng-repeat='p in famPeople'> {{p}}"
                       };
        });

控制器和指令:

myApp.controller("ctrl1",function($scope){
$scope.people=[1,4,6];
});

编辑

或者您可以将其作为属性传递并解析为数组:

<body ng-app="myApp" >
    <test-dir fam-people='[1,4,6]'> </test-dir>

</body>

指示:

var myApp = angular.module('myApp', []);

myApp.directive('testDir', function() {
                return { restrict: 'E', 
                        //scope: { famPeople: '=' },
                       template: "<ol> <li ng-repeat='p in people track by $index'> {{p}}",
                        link:function(scope, element, attrs){
                      scope.people=JSON.parse(attrs.famPeople);
                        }
                       };
        });

小提琴

2020-07-04