Angular trigger changes with $ watch vs ng-change, ng-checked, etc.

We can currently track data changes in several ways. We could initiate model changes with $watch , and we could add directives to the elements and associate some actions with it.

In many cases, this is a bit confusing, so I'm curious what the pros and cons of each option are, and when should we use the $watch binding, and when are directives like ng-change ?

+47
javascript angularjs angularjs-directive
Sep 25 '13 at 14:09
source share
4 answers

Both $watch and ngChange have completely different uses:

Suppose you have a model defined in the scope:

 $scope.myModel = [ { "foo":"bar" } ]; 

Now, if you want to do something when any changes happen to myModel , you should use $watch :

 $scope.$watch("myModel", function(newValue, oldValue){ // do something }); 

ngChange is a directive that evaluates a given expression when a user changes input:

 <select ng-model="selectedOption" ng-options="option for option in options" ng-change="myModel=selectedOption"></select> 

In short, you usually bind ngChange to some HTML element. While $watch for models.

+58
Sep 25 '13 at 14:21
source share

ngChange directive ngChange :

 var ngChangeDirective = valueFn({ require: 'ngModel', link: function(scope, element, attr, ctrl) { ctrl.$viewChangeListeners.push(function() { scope.$eval(attr.ngChange); }); } }); 

Guess that ngChange requires a controller from ngModel and executes a ngModel expression when the view changes.

So, it’s like an assistant that saves you from tedious tasks like [$ watch 'model] and then doing things].

In terms of performance, you have one lesser $watch expression to worry about.

+16
25 Sep '13 at 15:36
source share

Directives like ng-change are used to bind data to the DOM. $watch used in your JS code to listen for changes.

If you need the DOM to be affected by a change in your scope, or if you need to change the DOM changes (for example, a field), you must use the directive.

If you need to call JavaScript actions from a scope change, for example, an ajax request, then you should use $watch in your controller (or service) to listen for the changes.

+8
Sep 25 '13 at 14:14
source share

If you want two-way data binding, use ng-model . This pushes changes from model to presentation and from presentation to model in two ways. However, if you just want to bind one-way data binding to the model view, use ng-change . If you need a simple one-way data binding to the model for viewing, you can use the expression {{ like_this }} . But if you want to have a lot more control over how the model is displayed in the view, or if you want to bind the model to something other than the view, use $watch .

+1
Jun 09 '16 at 15:46
source share



All Articles