angularjs : logging scope property in directive link function displays undefined

前端 未结 3 2451
温柔的废话
温柔的废话 2021-02-20 17:30

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

相关标签:
3条回答
  • 2021-02-20 17:54

    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.

    0 讨论(0)
  • 2021-02-20 17:58

    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.

    0 讨论(0)
  • 2021-02-20 18:13

    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.

    0 讨论(0)
提交回复
热议问题