0

I have this:

        $scope.$watch('option.sCreatedBy', function (newValue, oldValue) {
            if (newValue && newValue !== oldValue) {
                _u.oyc.put('sCreatedBy', newValue);
                $scope.grid.data = null;
            }
        });

        $scope.$watch('option.sModifiedBy', function (newValue, oldValue) {
            if (newValue && newValue !== oldValue) {
                _u.oyc.put('sModifiedBy', newValue);
                $scope.grid.data = null;
            }
        });

Functionality is the same for all of these plus a few more than I don't show above.

Is there a way I could combine these watches into one watch and watch / modify multiple things at once ?

  • possible duplicate of [Can I combine watching of multiple fields into one watch with AngularJS?](http://stackoverflow.com/questions/17872919/can-i-combine-watching-of-multiple-fields-into-one-watch-with-angularjs) – WW. Mar 18 '14 at 04:54

1 Answers1

3

Right now, you're creating two identical, anonymous functions, then passing them to each $watch method. The second argument is just a callback function, so you might as well just name the callback function and pass the reference.

var watchCallback = function (newValue, oldValue) {
    if (newValue && newValue !== oldValue) {
        _u.oyc.put('sCreatedBy', newValue);
        $scope.grid.data = null;
    };
};
$scope.$watch('option.sCreatedBy', watchCallback);
$scope.$watch('option.sModifiedBy', watchCallback);

Another, and perhaps more Angular-ish approach would be to use $watchCollection instead of $watch:

$scope.$watchCollection('[option.sCreatedBy, option.sModifiedBy]', function (newValue, oldValue) {
    if (newValue && newValue !== oldValue) {
        _u.oyc.put('sCreatedBy', newValue);
        $scope.grid.data = null;
    };
});

It's important to note that the first argument to $watchCollection isn't an array, but instead a string looking like an array.

kba
  • 19,333
  • 5
  • 62
  • 89
  • $watchCollection looks good but How can I know which value is changed. Your answer has this: _u.oyc.put('sCreatedBy', newValue); but what if the sModified by is the thing that triggers the watch? Thanks –  Mar 18 '14 at 05:04