AngularJS - Access isolated scope in directive's link function

前端 未结 4 2122
北海茫月
北海茫月 2020-12-13 09:46

I\'m giving a first try at AngularJS custom directives.

I\'m having trouble using (or understanding ...) the isolated scope in the link function of the directive.

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-13 10:11

    Isolate scope properties bound with @ are not immediately available in the linking function. You need to use $observe:

    $attr.$observe('id', function(value) {
       console.log(value);
    });
    

    Your template works properly because Angular automatically updates isolate scope property id for you. And when it does update, your template automatically updates too.

    If you are just passing strings, you can simply evaluate the values once instead of using @ binding:

    link: function($scope, $elem, $attr) {
        var id    = $attr.id;
        var title = $attr.title
        console.log(id, title);
    }
    

    However, in your case, since you want to use the properties in templates, you should use @.

    If you weren't using templates, then @ is useful when attribute values contain {{}}s – e.g., title="{{myTitle}}". Then the need to use $observe becomes more apparent: your linking function may want to do something each time the value of myTitle changes.

提交回复
热议问题