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

Rob*_*b G 11 angularjs angularjs-directive

我创造了这个小提琴来展示我的问题......

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>
Run Code Online (Sandbox Code Playgroud)

这是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}}"
                   };
    });
Run Code Online (Sandbox Code Playgroud)

Moh*_*and 14

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

<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}}"
                       };
        });
Run Code Online (Sandbox Code Playgroud)

控制器和指令:

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

编辑

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

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

</body>
Run Code Online (Sandbox Code Playgroud)

指示:

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);
                        }
                       };
        });
Run Code Online (Sandbox Code Playgroud)

小提琴.


Fil*_*ype 14

当数组包含字符串时,JSON解析不起作用.

例如:

<file-handler fh-services="['BOX','DROPBOX']"></file-handler>
Run Code Online (Sandbox Code Playgroud)

在该指令中,您可以使用scope.$eval该属性将属性中显示的内容转换为数组.

scope.$eval(attrs.fhServices)
Run Code Online (Sandbox Code Playgroud)