为什么多次调用ng-repeat中的函数? [英] Why is a function in ng-repeat called several times?

查看:102
本文介绍了为什么多次调用ng-repeat中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过控制器功能提供一个ng-repeat元素,如下所示:

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
}

结果:我的allPictures函数被调用了几次,尽管我希望它只被调用一次,然后遍历结果.

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?

推荐答案

我真的避免在ngRepeat属性内部调用函数,因为它会产生错误和意外的行为.

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

但是,老实说,我认为您不需要在ngRepeat内部调用一个函数.我建议执行以下操作:

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

这样,将调用$scope.getPictures函数并创建$scope.allPictures. ngRepeat可以调用该集合而不是函数.

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.

另请参阅我的小提琴: https://jsfiddle.net/ABr/w6kc8qyh/1/

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

这篇关于为什么多次调用ng-repeat中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆