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>
And my exists function:
$scope.exists = function (optionNum) {
console.log('Inside $scope.exists. option: '+optionNum);
};
My timer:
function updateTimer() {
var onTimeout = function(){
mytimeout = $timeout(onTimeout,1000);
}
var mytimeout = $timeout(onTimeout,1000);
}
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 ?
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.
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.
So basically for instance in your case you could bind ng-checked to property
..ng-checked="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, like many of angular's directives are based on watches. Anytime a digest cycle is called, it evaluates all of the watchers (which the function you are using is one of). So every time $timeout evaluates it is starting a new $digest cycle and evaluating all of the watchers. This is part of the "magic" that keeps the view updated with all of the data in your controllers and directives.
Watchers can become a performance issue if you make your functions complex, or make TONS of watchers. It is generally best to have simple logic that returns true or false very quickly and to avoid setting watches on everything.
Related
I am trying to understand the Angular1 $digest cycle. I've read in multiple articles that the digest cycle is called multiple times on every change.
In this article it says:
So once we traversed all of the $watch functions in the $watch list, are we done with the $digest loop? No, we go through the list ONE more time and verify that nothing has changed. We do this because there could have been a change to one of the values when another $watch item updated it. We continue through this loop until no changes are present in any of the values.
So my question is - in what scenario there could have been a change to one of the values when another $watch item updated it?
this may not be the perfect example in real use cases, but things like this could happen.
$scope.$watch('Var_A', function(){
// change Var_B
});
$scope.$watch('Var_B', function(){
// do something
});
Var_A and Var_B are put into the $watch list.
Say that there is an angular change that changes Var_A, it triggers the first $digest cycle and Var_B changes. The first $digest cycle is not aware Var_B has changed. It then goes through the list one more time and will find that Var_B changes. After this, it goes through the list again and makes sure nothing in the $watch list got changed.
What are the performance implications of running a function within an Angular expression? For example:
<button ng-if="isValid()">Valid</button>
I'm assuming the function isValid() is being run for each digest loop, which occur many times per second. What options are available within Angular for improving the performance here?
One idea would be to run isValid() within a timeout function a few times a second, then setting a scope variable, so I can control the speed of the "digest". Are there other options people use?
I think if function body is just a simple logic comparison, won't affect performance, but if it gets complex, you can try profiling your code via chrome tools to see how much is performing,
Another alternative is also you can try binding the ng-if to a controller scope property instead and modify the value from other part of your controller's code, so maybe you can apply kind of debounce (https://github.com/shahata/angular-debounce) technique to avoid set the scope variable tons of times
It looks like you're checking if a form is valid before submitting. First of all, your ng-if on the button defeats the purpose of using the same function to conditionally apply a class, since it won't even be in the DOM if isValid() returns false.
You should be able to use ng-pattern, ng-change hooks on your inputs to determine validity as the user is entering form values. Then on your button you can apply the class based on the form's validity:
<button ng-class="{
'btn-success': myFormName.$valid,
'btn-danger': !myFormName.$valid
}" ng-bind="(myFormName.$valid) ? 'Valid' : 'Invalid'"></button>
If you want to suppress form submission, you can check validity of the form inside a function with ng-submit on the <form> tag:
<form name="myFormName" ng-submit="myFormName.$valid && mySubmitFunction()">
One way is to run the isValid function within an interval function, setting a simple scope variable within. For example:
$interval(function() {
scope.isvalid = scope.isValid();
}, 100);
This will run every 100ms, but is probably preferable to the number of calls the digest makes. You can also use $watch or $observe to reduce the number of calls.
one time binding for ng-disabled expression can be added like below: It works fine. No watcher is alive once isDisabled is resolved.
<text-area ng-disabled="::isDisabled"></text-area>
How can we add one way binding for ng-disabled with function. Tried like below but watcher was still present on the element.
<text-area ng-disabled="::isReadOnly(name)"></text-area>
Use like it.
<textarea ng-disabled="::{{test()}}"></textarea>
JS :
$scope.isDisabled = true;
$scope.test = function() {
return $scope.isDisabled;
}
The problem in my case is, there is no method called isReadOnly defined and since it will result in undefined, the watcher will be alive always since it could not come to stable position as specified in the Value stabilization algorithm in angular docs.
When digest loop is done and all the values have settled, process the queue of watch deregistration tasks. For each watch to be deregistered, check if it still evaluates to a value that is not undefined. If that's the case, deregister the watch. Otherwise, keep dirty-checking the watch in the future digest loops by following the same algorithm starting from step 1
Say that you want to do something when a property of $scope changes. And say that this property is bound to an input field. What are the advantages/disadvantages of using $watch vs. using ngChange?
html
<input ng-model="foo" ng-change="increment()">
<p>foo: {{foo}}</p>
<!-- I want to do something when foo changes.
In this case keep track of the number of changes. -->
<p>fooChangeCount: {{fooChangeCount}}</p>
js
// Option 1: $watch
$scope.$watch('foo', function() {
$scope.fooChangeCount++;
});
// Option 2: ngChange
$scope.fooChangeCount = 0;
$scope.increment = function() {
$scope.fooChangeCount++;
};
http://plnkr.co/edit/4xJWpU6AN9HIp0OSZjgm?p=preview
I understand that there are times when you need to use $watch (if the value you're looking to watch isn't bound to an input field). And I understand that there are times when you need to use ngChange (when you want to do something in response to a change in an input, but not necessarily in response to a scope property change).
However, in this case both accomplish the same thing.
My thoughts:
ngChange seems cleaner, and easier to understand what's happening.
$watch seems like it might be slightly faster, but probably negligible. With ngChange, I think Angular would have to do some extra work in the compile phase to set up the event listeners, and perhaps extra event listeners decrease speed a bit. Regardless of whether or not you use ngChange, the digest cycle runs on changes, so you have an opportunity to listen for something and call a function in response to changes.
Bottom line - You can achieve with $watch every thing you can achieve with ng-change but not vice-versa.
Purposes:
ngChange - binded to a HTML element
$watch - observing scope's model objects (HTML object models included)
My rule of thumb - if you can use ng-change use it to match your scenario, otherwise use $watch
Why you shouldnt use $watch?
It’s inefficient - Adding complexity to your $digest
It’s hard to test effectively
It's not clean
You have it mostly right. ng-change is very DOM specific and for evaluating an expression when the change event fires on a DOM element.
$watch however, is a lower-level (and more general purpose) utility that watches your view model or $scope. So your watch function will fire every time the user types a key (in the example of an input).
So to contrast, one listens to DOM events, the other watches your data.
$watch adds more complexity do the $digest, making it less efficient. In your case ngChange it's a cleaner and easier solution...
Font: http://www.benlesh.com/2013/10/title.html
I want to know about how the digest cycle works at back end of angularjs with respect to $watch
How does $watch handle a new value in comparison with the old value?
When the digest loop is called, how does $watch know the value change in angular's back-end?
Thank you!
$watch registers a listener function that is called whenever the given expression changes by comparing the old and new expressions with === in the digest loop.
This is pretty well explained in the docs
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch
I am not sure what you mean by back-end. I am assuming that you are asking how do you know if some other action has changes your model object, value etc.
Here is some pseudo example..
scope.$watch('lastLatency', function (val) {... you got your new value here ....}
In this example "lastLatency" value is being watched to take action.