Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cant I pass an element attribute to scope.$watch but i can pass a function that returns it

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.

like image 439
user7986267 Avatar asked Jan 31 '26 14:01

user7986267


1 Answers

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.

like image 159
Karim Avatar answered Feb 02 '26 04:02

Karim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!