13

In Angular 1.3 it's possible to use this.foo='bar' insteaod of $scope.foo='bar'. Now, how can I use $watch without $scope?

Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173
  • The short answer seems to be no, because $watch is a $scope method, but elaborate: What's the use-case, what is the scope of the variable you want to observe? – doldt Feb 05 '15 at 12:39
  • Depending on what you are trying to do you can use [ng-change](https://docs.angularjs.org/api/ng/directive/ngChange) if you just need to observe a change on an input field – Wayne Ellery Feb 05 '15 at 12:47
  • Indeed I need to watch any change to any filed of a model. – Handsome Nerd Feb 05 '15 at 12:49
  • `$watch` has very specific abilities, [here are some examples](http://stackoverflow.com/a/29189252/1175496) , the most powerful use-case involves `$watch(.., .., true)` on an array, which detects array re-assignment, array modification, and array element modification. Can `ng-change` replace this ability? – Nate Anderson Apr 16 '17 at 02:06

1 Answers1

19

There are several options to avoid having to use $watch when using the controller as syntax.

The following examples are taken from a blog post I wrote about avoiding $scope.

Using ng-change

If you have a watch set up to listen for a property change that originates from a form field, then ng-change is your best bet.

<input type="text" ng-model="ctrl.name" ng-change="ctrl.search(ctrl.name)" />

MyCtrl.prototype.search = function(name){
  //call some service here
};

Using ES5 Properties

If you have some property that isn't bound to an input field, or is going to be updated from code, it may seem like a watch is your only choice. However, if you don't have to support IE8 or lower, then you can take advantage of ES5 properties to trigger functionality when something changes on your controller.

var MyCtrl = function(){
  this._selectedItem = null;
};

Object.defineProperty(MyCtrl.prototype,
    "selectedItem", {
    get: function () {
        return this._selectedItem;
    },
    set: function (newValue) {
        this._selectedItem = newValue;

        //Call method on update
        this.onSelectedItemChange(this._selectedItem);
    },
    enumerable: true,
    configurable: true
});
Josh
  • 44,706
  • 7
  • 102
  • 124