我创建了这个 fiddle 来显示我的问题...
我将一个新创建的数组传递给一个指令,一切都很顺利。但是,我在控制台窗口中收到错误消息,指示:
错误:[$rootScope:infdig] 已达到 10 次 $digest() 迭代。正在中止!
对于我需要按摩什么来清理它有什么想法吗?我希望能够重复使用该指令,而无需更新 Controller 。
这是 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}}"
};
});
最佳答案
该错误是因为您的指令无法将数组解释为数组,请尝试以下操作:
<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}}"
};
});
Controller 和指令:
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);
}
};
});
参见fiddle .
关于angularjs将属性中新创建的数组传递给指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20811527/