0

I've an array and I'm looping over this array and calling a function into this ng-repeat and this function is in link function of a directive so my problem is, ng-repeat looping only twice (length of array items) but calling directive link function more than twice Here my code snippet

link:function(scope){ 
      $scope.test = function() {
        console.log('sssss');
     }}

and template is

<div ng-repeat ="item in items> {{test()}}></div>

please help me to prevent calling test function more than items length.

Ravi Teja
  • 1,097
  • 8
  • 13
Mhd Wael Jazmati
  • 636
  • 9
  • 18

2 Answers2

1

You should do this,

<div ng-repeat ="item in items" ng-init="test()"> </div>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

Reason test() is getting called more times than length of array items is because of this {{test()}}.

AngularJS registers a watcher for {{}}(binding) in view.

This watcher keeps track of whether value has been changed or not(it compares the old value to new value). watcher's expression(in your case, test()) gets evaluated atleast once in this process.

You can read more about it here.

Thats the reason your test() is getting more number of times than length of array.

<div ng-repeat ="item in items" ng-init="test()"> </div>

If you use ng-init, test() will only be initialized(called) once per each repeat.

Community
  • 1
  • 1
Ravi Teja
  • 1,097
  • 8
  • 13