When should I use angular $watch
functions and when use ng-change
angularjs directive? To me, they both can do the same.
Are there any differences or usage patterns between them?
$watch() function is used to watch the changes of variables in $scope object. Generally the $watch() function will create internally in Angularjs to handle variable changes in application.
The ng-change event is triggered at every change in the value. It will not wait until all changes are made, or when the input field loses focus. The ng-change event is only triggered if there is a actual change in the input value, and not if the change was made from a JavaScript.
Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.
Ng-change is a directive in AngularJS which is meant for performing operations when a component value or event is changed. In other words, ng-change directive tells AngularJS what to do when the value of an HTML element changes. An ng-model directive is required by the ng-change directive.
They are not the same, clearly. One is used solely in the controller; the other is a directive on an input element.
But even in their application they differ.
When you use $watch
the watched expression will be evaluated on every digest cycle, and if there is a change, the handler is invoked.
With ng-change
, the handler is invoked explicitly in response to an event.
With $watch
, change can come from anywhere: user action, controller function, service - all will trigger the handler.
With ng-change
, the change is restricted to a user action on a particular input element.
It is worth to note also that ng-change
works only in combination with ng-model
- in other words, the ng-change
expression is evaluated only when ngModel.$viewValue
(refer to ngModelController
documentation for more info) is changed, which typically happens in response to a user-initiated event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With