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

标签 angularjs angularjs-directive

我创建了这个 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/

相关文章:

javascript - Angular 1.5 测试组件与 jasmine

javascript - 使用 ui.bootstrap 显示部分内容

javascript - Angular 的第三级点表示法?

javascript - 在使用 AngularJS 动态设置样式时访问样式属性

javascript - Angular JS 动态模板文件

angularjs - 嵌入指令中的访问父范围

javascript - Angularjs 指令 : child nodes

javascript - 如何使用 Angularjs 在加载时显示图像?

带有条件表达式的 AngularJS ng 风格

javascript - AngularJS Controller 变量未传递给子指令