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

时间:2013-12-28 05:55:06

标签: 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>

这是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}}"
                   };
    });

3 个答案:

答案 0 :(得分: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}}"
                       };
        });

控制器和指令:

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

答案 1 :(得分:14)

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

例如:

<file-handler fh-services="['BOX','DROPBOX']"></file-handler>

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

scope.$eval(attrs.fhServices)

答案 2 :(得分:0)

怎么样:

<body ng-app="myApp">
    <test-dir fam-people='1;4;6'> </test-dir>
    <test-dir fam-people='2;1;0'> </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= attrs.famPeople.split(';');
                        }
                       };
        });

最干净的解决方案?

相关问题