I\'m interested to find out why i always have to do this
$scope.$watch( function() {
return $scope.someData;
}, function( value ) {
console.log( value
Since the how-to-do answer is already given, I'll try to explain you what goes on actually and why it didn't work the way you tried at first time.
First of all this code sure works,
$scope.$watch(function() {
return $scope.someData;
}, function(value) {
console.log(value);
});
But this is NOT the perfect way. To be more precise $watch
injects the scope
in the function, like this,
$scope.$watch(function(injectedScope) {
return injectedScope.someData;
}, function(value) {
console.log(value);
});
Previously it works because $scope
and injectScope
are one and the same thing.
Now as this article explains,
Since
$scope
is passed into the watch function, it means that we can watch any function that expects the scope as an argument and returns a value in response. A great example of this is $interpolate function.
So in your case, we can also make use of $interpolate
as following:
$scope.$watch($interpolate("{{someData}}"), function(value) {
...
});
Now this is where we come to the short-hand method of using just a watch expression.
$watch
can also accept an expression, which actually is interpolated.
Thus by providing $scope.$watch("someData", ... )
,
someData
will be:
{{someData}}
$watch
functionThis is a nice, clean, readable, short-hand way of writing the expression instead of the actual function. But finally after all such compilations, it is ultimately the function which returns a value to watch.