3

I want to supply a ng-repeat element by a controller function as follows:

<div ng-repeat="picture in allPictures(data.pictures)"></div>
$scope.allPictures = function(pictures) {
        alert("function called");
    //return... extract all pictures and return as array
}

Result: my allPictures function is called several times, even though I'd expect it to be called only once and then iterate over the results.

Why? And moreover: how can I prevent this and really call the method only once for picture supply?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • ["...will execute multiple times in a single $digest cycle if a change is detected."](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch) – John Strickler Aug 11 '15 at 12:56
  • 2
    Call it in the controller, set returned value as a property on scope or controller and then `ng-repeat` _that_ instead. – Sergio Tulentsev Aug 11 '15 at 13:00
  • try to avoid using functions for display in view due to digest cycles. Event handlers obviously are different – charlietfl Aug 11 '15 at 13:05
  • In no way. You must prepare data in controller. [Some info](http://stackoverflow.com/questions/12336897/how-to-loop-through-items-returned-by-a-function-with-ng-repeat) – user3335966 Aug 11 '15 at 13:09

2 Answers2

4

I would really avoid calling a function insides a ngRepeat attribute, since it will give errors and unexpected behaviour.

But to be honest I dont think that you would need to call a function inside a ngRepeat. I would suggest to do the following:

<div ng-repeat="picture in allPictures"></div>
$scope.getPictures = function(pictures) {
        alert("function called");
        //return... extract all pictures and return as array
};

$scope.allPictures = $scope.getPictures();

This way the $scope.getPictures function will get called and the $scope.allPictures will be created. ngRepeat can call that collection instead of a function.

See also my Fiddle: https://jsfiddle.net/ABr/w6kc8qyh/1/

georgeawg
  • 48,608
  • 13
  • 72
  • 95
ArBro
  • 731
  • 5
  • 18
1

a little bit about the digest cycle:

we need to check every time something in the application changes - what was effected by that change, and re-evaluate all the places that might depend on that change,

so that is why the function in the ng-repeat was called multiple times - it had to check wheter the repeated list is the same after some changes happend in the application

read more about the digest cycle and two-way data binding:

http://blog.bguiz.com/post/60397801810/digest-cycles-in-single-page-apps/

MoLow
  • 3,056
  • 2
  • 21
  • 41