Why can't I pass the element attribute to the scope. $ Watch, but I can pass a function that returns it
I wrote a watchId directive 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 is working correctly, but my question is why I cannot do scope.$watch(elem.attr('id'), function(newValue) {
I don't think it will be necessary, but here is a JSfiddle where I am playing around with the above.
source to share
because elem is not a field $scope
(but a service introduced by angular) and this syntax is only valid for a property in a service $scope
.
You can think of it as a "shortcut".
eg
$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 look at is not part of an object $scope
, you must register the function as the first argument that will run every digest loop to check for changes.
why do i need a function?
the function you pass to the observer is a closure and has outer scope access, which means all outer scope variables including elem
.
source to share