Now that the step-by-step guide has been provided, let me delve into explaining the actual process and the reasons behind why your initial attempt didn't yield the desired results.
To start off, the code you used does work as intended,
$scope.$watch(function() {
return $scope.someData;
}, function(value) {
console.log(value);
});
However, this method is not flawless. To be more specific, when using $watch
, the scope is injected into the function in the following manner,
$scope.$watch(function(injectedScope) {
return injectedScope.someData;
}, function(value) {
console.log(value);
});
Initially, it seemed to work because both $scope
and injectScope
refer to the same object.
As elaborated in this article,
By passing $scope
into the watch function, it enables us to monitor any function that requires the scope as an argument and generates a corresponding value. One such illustrative example is the $interpolate
function.
In your scenario, you can also opt for the $interpolate
method like so:
$scope.$watch($interpolate("{{someData}}"), function(value) {
...
});
This brings us to the shortcut approach of utilizing a watch expression directly. $watch
can receive an interpolated expression as well.
Hence, by employing $scope.$watch("someData", ... )
,
someData
will undergo:
- interpolation as
{{someData}}
- utilization of the scope provided by the
$watch
function
This serves as a succinct, comprehensible, shorthand way of formulating the expression rather than resorting to the complete function syntax. Nonetheless, amidst all these refinements, it is ultimately the function that returns the observable value.