AngularJS 中没有独立范围的指令范围属性 [英] Directive scope attributes without an isolated scope in AngularJS
问题描述
有没有办法在继承父作用域的同时用传递的属性扩展它?
我想直接从模板将参数传递给可重用指令,而无需更改链接函数中的 DOM.
例如:
<form-input icon="icon-email" label="email" ng-model="data.input"></form-input>
对于这样的指令:
<label>{{label}}</label><div class="input-group"><div class="{{icon}}">@</div><input class="form-control" placeholder="Email" ng-model="mail.email">
ng-model 在父作用域中,在这种情况下控制整个表单,但我认为没有必要在控制器中存储样式属性.
有没有办法直接在模板中传递参数而不创建隔离作用域?
您将无法扩展"父范围.但是,您的目标可以通过使用指令的链接函数中注入的指令标记属性来实现.
所以例如.为了附加 label
变量,指令的链接函数如下所示:
链接:函数 ($scope, $element, $attributes) {$scope.label = $scope.$eval($attributes.label);}
您可以查看下面的 plunker 进行现场演示.
http://plnkr.co/edit/2qMgJSSlDyU6VwdUoYB7?p=preview
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 from the template without having to alter the DOM in the linking function.
For example:
<form-input icon="icon-email" label="email" ng-model="data.input"></form-input>
For a directive like this:
<div class="form-group">
<label>{{label}}</label>
<div class="input-group">
<div class="{{icon}}">@</div>
<input class="form-control" placeholder="Email" ng-model="mail.email">
</div>
</div>
ng-model is in the parent scope, controlling an entire form in this case, but I don't think it's necessary to store styling attributes in the controller.
Is there a way of passing parameters directly in the template without creating an isolate scope?
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
这篇关于AngularJS 中没有独立范围的指令范围属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!