问题
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?
回答1:
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.
回答2:
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.
回答3:
For those in 2015 who are reading this post, please note that the way Angular handles "@"
attributes has changed.
Angular 1.2 onwards, interpolation occurs prior to the invocation of the linking function.
An excellent post on this topic is present here.
来源:https://stackoverflow.com/questions/14552024/angularjs-logging-scope-property-in-directive-link-function-displays-undefined