当完全被ng-checked调用 [英] When exactly is ng-checked called
问题描述
使用AngularMaterial时,我有 ng-checked
:
While using AngularMaterial, I have ng-checked
like this:
<md-list>
<md-list-item ng-repeat="option in options">
<p> {{ option }} </p>
<md-checkbox class="md-secondary" aria-label="{{$index}}" ng-checked="exists($index)" ng-click="toggle($index)"></md-checkbox>
</md-list-item>
</md-list>
和我的存在函数:
$scope.exists = function (optionNum) {
console.log('Inside $scope.exists. option: '+optionNum);
};
我的计时器:
function updateTimer() {
var onTimeout = function(){
mytimeout = $timeout(onTimeout,1000);
}
var mytimeout = $timeout(onTimeout,1000);
}
这样, $ scope.exists
函数每秒被调用。有人可以解释一下
ng-checked
和 $ timeout
相关吗?如何避免这种情况?
With this, the $scope.exists
function is getting called every second. Can someone please explain how ng-checked
and $timeout
related ? and how to avoid this ?
推荐答案
一个字的原因是: digest cycle 。因为你的函数被绑定到视图,每次摘要周期发生时,这些表达式被评估为脏检查的一部分,以确保相应的DOM是否需要更新。这与角材料单独无关,它是核心角实现。现在在你的情况下,你调用 $ timeout
无限,这意味着在每个超时执行 digest
周期发生执行脏检查。
Reason in one word is: digest cycle. Since your function is bound to the view, every time digest cycle happens those expressions gets evaluated as a part of dirty check to make sure if respective DOM needs to be updated or not. This is nothing to do with angular material alone, it is the core angular implementation. Now in your case you are calling $timeout
infinitely which means after each timeout execution digest
cycle happens to perform dirty check.
现在你已经很好了,但是每当你绑定一个函数到DOM(作为视图绑定的一部分,插值或属性状态属性,甚至DOM过滤器 - 当然事件很好),你应该知道这个事实,你不会在应用程序增长意外或故意执行广泛的操作,它会减慢整个应用程序,并将很难重构和诊断,当应用程序变得更大,问题开始发生。尽可能地绑定到一个属性而不是一个函数。注意,即使你绑定一个属性仍然有角度
$ parse
创建一个getter并添加到 $$ watchers
Now what you have is fine, but whenever you bind
a function to DOM (as a part of view binding, interpolation or property state attributes or even DOM filters - of course events are fine) you should be aware of the fact that you do not perform extensive operation in that function accidentally or intentionally as the app grows, it will slow down the entire app, and will be hard to refactor and diagnose when the app grows larger and problems starts happening. As much as possible bind to a property instead of a function. Note that even if you bind a property still angular $parse
creates a getter on it and adds it to the $$watchers
queue to be dirty checked every digest cycle, but difference is that it is a simple getter function.
因此,基本上例如在你的情况下,你可以绑定 ng-checked
到属性
So basically for instance in your case you could bind ng-checked
to property
..ng-checked="doesExist"
并在需要更新时设置属性 doesExist
。所以使用这个而不是每次检查的存在,你明确设置相应的属性,当相应的事件发生时。这使得逻辑也是明确的。
and set the property doesExist
whenever it needs to be updated. So with this instead of checking for the existence every time, you explicitly set the respective property when a respective event happens. That makes the logic explicit as well.
这篇关于当完全被ng-checked调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!