问题描述
我只是想知道为什么在下面的jsfiddle这里是一个LO打印三次。
I just want to understand why in the following jsFiddle 'here is a lo' is printed three times.
$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.
推荐答案
角用途消化周期/迭代来确定何时状态已发生变化,需要更新的用户界面。如果它发现它的周期之一的任何改变,它保持,直到数据稳定本身重新运行周期。如果它做了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()}}。如果它改变角度不断评估前pression看到的。
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()假设它返回的东西,而不是仅仅写到控制台],并在指令中使用的模板{{登录}}。通过这种方式,你会得到价值只有一次,每个控制器实例。
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.
希望我是很清晰。
这篇关于需要对角direcive负荷解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!