I wrote a directive watchId with the following code
.directive('watchId', function(){
return {
restrict: 'A',
link: function(scope, elem, attr) {
scope.$watch(function() { return elem.attr('id') }, function(newValue){
if (newValue) {
scope.loaded[newValue] = true
}
})
}
}
})
The above code works correctly but my question is why cant i just do scope.$watch(elem.attr('id'), function(newValue) {
I dont think it will be needed but here is a JSfiddle where Im playing with the above.
because elem is not a $scope field (but a service injected by angular) and that syntax is valid only for property under the $scope service.
You can consider it like a "shortcut".
for example
$scope.stuff = {}
$scope.$watch('stuff', function(newVal){
//this is valid because stuff is a property of the $scope object
})
if the property you want to watch is not part of the $scope object you must register a function as tthe first argument that will be triggered every digest cycle to check for changes.
why you need a function?
the function you pass to the watcher is a closure and has access to the outer scope, that means all the outer scope variables including elem.
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