Why is a function in ng-repeat called several times?

后端 未结 2 1709
梦谈多话
梦谈多话 2021-01-21 06:47

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

相关标签:
2条回答
  • 2021-01-21 07:25

    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/

    0 讨论(0)
  • 2021-01-21 07:26

    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/

    0 讨论(0)
提交回复
热议问题