需要对角方向载荷进行解释 [英] Need explanation on a angular direcive load

查看:36
本文介绍了需要对角方向载荷进行解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想了解为什么在下面的 jsFiddle 中 'here is a lo' 被打印了 3 次.

I just want to understand why in the following jsFiddle 'here is a lo' is printed three times.

http://jsfiddle.net/wg385a1h/5/

$scope.getLog = function () {
    console.log('here is a log');
 }

谁能解释一下为什么?我应该更改为只有一个日志这是一个日志"(这就是我希望这个小提琴做的事情).非常感谢.

Can someone explain me why ? What should I change to have only one log "here is a log" (that's what I would like this fiddle do). Thanks a lot.

推荐答案

Angular 使用摘要循环/迭代来确定状态何时发生变化并需要更新 UI.如果它发现其中一个周期有任何变化,它会继续重新运行周期,直到数据稳定下来.如果它完成了 10 个周期并且数据仍然在变化,你会看到一个相当清楚的消息:angularjs 10 次迭代达到.中止".

Angular uses digest cycles/iterations to determine when state has changed and needs to update the UI. If it finds any change on one of it's cycles, it keeps rerunning cycles until the data stabilizes itself. If it's done 10 cycles and the data is still changing, you'll see a rather know message: "angularjs 10 iterations reached. aborting".

因此,您看到该消息显示 3 次的事实是因为您有一个简单的界面.事实上,由于您的指令使用了 {{getLog()}},因此您可以在日志中获得更多此类消息.Angular 不断评估表达式以查看它是否发生了变化.

Therefor, The fact that you are seeing the message displayed 3 times is because you have a simple interface. In fact, you can get up to many more such messages in the log, due to the fact that your directive uses {{getLog()}}. Angular keeps evaluating the expression to see if it changed.

为避免此类问题,在正常情况下,您应该在控制器内的 $scope 对象中存储您只想调用一次的函数的返回值,并在 UI 中使用该变量(而不是函数调用).

To avoid such problems, under normal circumstances, you should store the value returned by the function you want called only once in the $scope object inside the controller and use that variable (not the function call) in the UI.

因此,在控制器中,您将拥有 $scope.log = getLog() [假设它返回某些内容,而不仅仅是写入控制台],并且在指令中使用模板 {{log}}.这样,对于每个控制器实例,您只会获得一次该值.

So in the controller you'd have $scope.log = getLog() [assuming it returns something, and not just writing to the console] and in the directive use the template {{log}}. This way, you'll get the value only once, per controller instance.

希望我说得够清楚了.

这篇关于需要对角方向载荷进行解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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