Samantha J T Star
Samantha J T Star

Reputation: 32778

Is there any difference between using a $watch and ng-change to detect the change in a select list?

I've been using code like to watch in this case a couple of select dropdown lists:

   this.$watchCollection('[config.statusId, config.typeId]',
        function (newValue, oldValue) {
            if (_o.checkWatch(newValue, oldValue)) {
                _u.putConfigs(this.config);
                home.grid.backup = [];
                home.grid.data = [];
            }
        }.bind(this));

   var _checkWatch = function (newValue, oldValue) {
       for (var i = 0, l = newValue.length; i < l; i++) {
           if (newValue[i] === null || newValue[i] < 0 || newValue[i] >= 999
            || oldValue[i] === null || oldValue[i] < 0 || oldValue[i] >= 999)
               continue;
           if (newValue[i] !== oldValue[i]) {
               return true;
           }
       }
       return false;
   };

I was unaware of ng-change and I am now thinking it may be better to use that for detecting when a user changes the value in a select list. With ng-change I could then call a function to do:

   _u.putConfigs(this.config);
   home.grid.backup = [];
   home.grid.data = [];

With this in mind can anyone think of a reason why I should not go to ng-change to detect when a user makes a change?

Upvotes: 0

Views: 208

Answers (1)

MBielski
MBielski

Reputation: 6620

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 (not to mention that it appears to be less code in your case.)

Upvotes: 1

Related Questions