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
Related
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.
From my understanding $attr.$observe fires once. So there are times to use $watch on an attribute. I am looking to unit test a directive that requires ngModel
scope.$watch(attr.ngModel, function (newValue) {
minlength = parseInt(attr.minLength);
scope.minLengthValidator(newValue);
});
Since this is using scope in the Link function it seems like I could call $digest.
My mocked attribute starts like so...
html = angular.element("<input ng-model=\"myUnit\" min-length=\"3\">");
I am not sure if I can just redefine element.attr('min-length') inside of my spec and run a $digest or if there is a more complex approach since the the watch is passing a new value.
the rest of my mock set up is like so
$rootScope = $rootScope.$new();
element = $compile(html)($rootScope);
$rootScope.$digest(element);
controller = element.controller('ngModel');
scope = element.scope();
I have not tested a $watch on a attribute before so any direction that points me towards solving this would be much appreciated.
scope.$watch(attr.ngModel, ...) will create a watcher on myUnit scope property. Once the watcher is created, it isn't bound to ngModel attribute value.
It can be tested as any other scope watcher:
scope.myUnit = ...;
$rootScope.$digest();
expect(scope.minLengthValidator).toHaveBeenCalledWith(...);
From my understanding $attr.$observe fires once.
No, $attrs.$observe observer will fire on each attribute change, it is preferable to $scope.$watch. As the manual states,
Use $observe to observe the value changes of attributes that contain
interpolation (e.g. src="{{bar}}"). Not only is this very efficient
but it's also the only way to easily get the actual value because
during the linking phase the interpolation hasn't been evaluated yet
and so the value is at this time set to undefined.
The problem is that attributes belong to DOM and can't be tested cleanly. For controller specs $attrs local dependency can be mocked, but it isn't possible in directive specs. For testability reasons it is preferable to bind attributes to scope properties and test the scope only with no $attrs involved.
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
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.
I already know that you can use attr.$observe within a directive to watch the attributes if they change.
Is there an equivalent to watch the text within an element?
<div my-directive ng-bind="myText || 'Watch me!!!'">Watch me!!!</div>
In the above example, I'd want to watch the text "Watch me!!!". I'd much prefer to do this rather than $watch what is being bound to the directive because of scoping issues.
Watching the DOM for changes is EXPENSIVE, also there is no built in way within Angular to do so. Watching the scope for changes is the correct way to do this.
If you are having issues with scoping then perhaps, with more I formation,that is something we could help with as well.
It's possible to watch DOM changes, here's an example:
http://jsfiddle.net/kihu/t7zr71ma/5/
The trick is to pass a function returning anything you want to watch, e.g.:
scope.$watch(function () {
return element.text();
}, handleChange)
But I think #Enzey is right, you should avoid watching the DOM, instead you should bind data from angular scope and watch it.