Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs pass newly created array in attribute to directive

I've created this fiddle to show my issue...

http://jsfiddle.net/dQDtw/

I'm passing a newly created array to a directive, and everything is working out just fine. However, I'm getting an error in the console window indicating:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!

Any thoughts on what I need to massage to clean this up? I'd like to be able to reuse the directive without the need to update the controller.

Here is the html

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

Here is the 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}}"
                   };
    });
like image 907
Rob G Avatar asked Dec 28 '13 05:12

Rob G


1 Answers

That error is because your directive is not able to interpret the array as an array, Try this:

<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 and directive:

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

EDIT

or you could pass it in as an attribute and parse it to an array:

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

</body>

Directive:

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);
                        }
                       };
        });

See fiddle.

like image 79
Mohammad Sepahvand Avatar answered Oct 18 '22 14:10

Mohammad Sepahvand