gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:57:38 26 4
gpt4 key购买 nike

我创建了这个 fiddle 来显示我的问题...

http://jsfiddle.net/dQDtw/

我将一个新创建的数组传递给一个指令,一切都很顺利。但是,我在控制台窗口中收到错误消息,指示:

错误:[$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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com