简体   繁体   English

控制器功能被多次调用

[英]Controller function gets called multiple times

I have done some research both at Google and StackOverflow, and found several similar questions, but none seem to solve nor address my specific case. 我在Google和StackOverflow上做了一些研究,发现了几个类似的问题,但似乎没有解决也没有解决我的具体案例。 So here is my question: 所以这是我的问题:

In some code I am working on I am calling a controller function from my html, like this: 在我正在处理的一些代码中,我正在从我的html调用控制器函数,如下所示:

<div ng-controller="MyCtrl">
  <p>{{ myFunction() }}</p>
</div>

And since in myFunction I do some tracing, I noticed the function gets called 4 times! 因为在myFunction中我做了一些跟踪,我注意到函数被调用了4次!

I have created a minimalistic test at JS Bin, here: http://jsbin.com/nukuhemata/1/edit?html,js,console,output 我在JS Bin创建了一个简约测试,在这里: http//jsbin.com/nukuhemata/1/edit?html ,js,console, output

In this reduced test, my function gets called 3 times (there is some progress ;-). 在这个简化的测试中,我的函数被调用了3次(有一些进展;-)。 And if instead of {{ test() }} I use {{ ::test() }} as suggested in some other answers I have seen, it gets called only twice (some more progress). 如果不是{{ test() }}我在我看到的其他一些答案中建议使用{{ ::test() }} ,它只会被调用两次(更多的进展)。

I am a beginner at Angular, from what I have read I think it is the normal, expected behavior. 我是Angular的初学者,从我读过的内容来看,我认为这是正常的,预期的行为。 Is that so? 是这样吗? If it is, why? 如果是,为什么? If not, what is wrong in my code? 如果没有,我的代码有什么问题?

It's normal behavior, every time a $digest cycle runs, the function must be executed to check whether the output value has change, and thus whether there's a new value to update the DOM with. 这是正常的行为,每次$digest循环运行时,必须执行该函数以检查输出值是否有变化,从而是否有更新DOM的新值。

Because of this, it's better practice to update a value on the $scope from the controller when needed, and reference that in your markup. 因此,最好在需要时从控制器更新$scope的值,并在标记中引用它。 Usually not a meaningful difference, but if your function is building up a large array for a ng-repeat , it can become a big deal. 通常不是一个有意义的差异,但如果你的函数正在为一个ng-repeat构建一个大数组,那么它可能会变得很重要。

Edit: See function called multiple times from template for a more robust answer. 编辑:查看从模板多次调用的函数,以获得更强大的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM