Directive scope attributes without an isolated scope in AngularJS

后端 未结 2 1758
鱼传尺愫
鱼传尺愫 2021-01-03 20:38

Is there a way of inheriting the parent scope while extending it with passed attributes?

I want to pass parameters to a reusable directive directly

相关标签:
2条回答
  • 2021-01-03 20:57

    You would not be able to 'extend' the parent scope as such. However your objective can be accomplished by utilizing the directive tag attributes that are injected in the link function of your directive.

    So eg. for attaching your label variable, your directive's link function would look like below:

     link: function ($scope, $element, $attributes) {
             $scope.label = $scope.$eval($attributes.label);
            }
    


    You can check out the below plunker for a live demo.
    http://plnkr.co/edit/2qMgJSSlDyU6VwdUoYB7?p=preview

    0 讨论(0)
  • 2021-01-03 20:57

    The answer from Angad will work for static linking, but if the value of the attribute can change after linking, this will not be updated. If you need this, the sollution would be to pass the value as string instead of reference:

    <form-input icon="icon-email" label="{{email}}" ng-model="data.input"></form-input>
    

    In the directive, add an $observe on the attribute to update the scope variable:

    $attributes.$observe('label', function(newValue){$scope.label=newValue});
    

    Now the scope variable will dynamically change if the attribute value change.

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