Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs : logging scope property in directive link function displays undefined

I have this basic plnkr which just implements a basic "Hello, X" directive. In the link function I am logging scope.name but I get undefined? Why is it so? Shouldn't it log the value of name property in console?

like image 819
Jatin Avatar asked Jan 27 '13 20:01

Jatin


2 Answers

This is a known "problem" where interpolation of @ attributes happens after linking function is invoked. There is a pull request open to change this issue but it is not clear if this one is going to be merged.

In the meantime a way of getting an interpolated value is by observing an attribute like so:

attrs.$observe('hello', function(changedValue){
     console.log(scope.name);
});

And the plunk: http://plnkr.co/edit/Lnw6LuadTLhhcOTsPC8w?p=preview

So, at the end of the day this is a bit confusing behavior of AngularJS that might be changed in the future.

like image 108
pkozlowski.opensource Avatar answered Nov 13 '22 17:11

pkozlowski.opensource


Pawel is right (https://stackoverflow.com/a/14552200/287070) but I wanted to add that the problem is that any attribute that contains {{}} interpolation will be set to null in the attrs parameter during the link function as the first $digest since the compilation has not yet run to evaluate these.

The fact that @ bindings are null in linking functions is just a symptom of this.

Currently there is no real fix, since we can't start running $digests in the middle of the compilation process. So $observe (or $watch) is the only real way to get hold of these values.

like image 2
Pete BD Avatar answered Nov 13 '22 17:11

Pete BD