Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to $watch multiple variables?

I do have two $scope variables. They are called $scope.image and $scope.titleimage.

Basically the store the same type of contents. I want to track now when either one of them gets updated. But so far I could not figure out how to have two variables tracked in a single $scope.$watch() callback.

// How can I watch titleimage here as well?
$scope.$watch('image', function(media) {
    console.log('Media change discoverd!');
}); 
like image 370
powtac Avatar asked Jul 09 '13 14:07

powtac


2 Answers

$watch method accepts a function as first parameter (beside a string). $watch will "observe" the return value of the function and call the $watch listener if return value is changed.

$scope.$watch(
  function(scope){
    return {image: scope.image, titleImage: scope.titleImage};
  }, 
  function(images, oldImages) {
    if(oldImages.image !== images.image){
      console.log('Image changed');
    }
    if(oldImages.titleImage !== images.titleImage){
      console.log('titleImage changed');
    }
  }, 
  true
); 

Also you might observe a concatenated value, but that doesn't let you know which one of the observed values actually changed:

$scope.$watch('image + titleImage',
  function(newVal, oldVal) {
    console.log('One of the images have changed');
  }
); 

And you can also watch an array of scope variables:

$scope.$watch('[image, titleImage]',
  function(images, oldImages) {
    if(oldImages[0] !== images[0]){
      console.log('Image changed');
    }
    if(oldImages[1] !== oldImages[1]){
      console.log('titleImage changed');
    }
  },
  true
); 
like image 158
Stewie Avatar answered Sep 20 '22 02:09

Stewie


Stewie's suggestions will work. But there are a thousand ways to skin this cat. I'd submit that if you're watching two separate values, there's nothing wrong with setting up two watches for them with a shared function between them:

functional programming to the rescue!

Using functions to create functions is awesome.

function logChange(expr) {
   return function(newVal, oldVal) {
      console.log(expr+ ' has changed from ' + oldVal + ' to ' + newVal);
   };
}

$scope.$watch('image', logChange('image'));
$scope.$watch('titleImage', logChange('titleImage'));

OR... you could even wrap the watch setup in it's own function (much less exciting, IMO):

function logChanges(expr) {
   $scope.$watch(expr, function(newVal, oldVal) {
      console.log(expr+ ' has changed from ' + oldVal + ' to ' + newVal);
   });
};

logChanges('image');
logChanges('titleImage');

.. but I have a thousand of them, you say?

//assuming the second function above
angular.forEach(['image', 'titleimage', 'hockeypuck', 'kitchensink'], logChanges);
like image 29
Ben Lesh Avatar answered Sep 19 '22 02:09

Ben Lesh