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!');
});
$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
);
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:
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'));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With