43

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?

levi
  • 22,001
  • 7
  • 73
  • 74
  • $watch and ng-change does roughly the same thing, but their use cases are different. – Ved Feb 04 '15 at 05:13
  • 1
    The $watch will check the values (old and new) and compare them every time anything causes the Angular $digest cycle to run. Using ng-change does roughly the same thing, but I believe it is syntactically more correct to use. – Anil Singh Feb 04 '15 at 05:23
  • Another question quite similiar : http://stackoverflow.com/questions/19007281/angular-trigger-changes-with-watch-vs-ng-change-ng-checked-etc – Qianyue Mar 06 '15 at 15:36

1 Answers1

92

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.

New Dev
  • 48,427
  • 12
  • 87
  • 129