I have a custom element directive with the following template:
<div>
<input value="{{dataFromRootScope}}" />
</div>
And definition:
dirModule.directive('myDirective', function() {
return {
restrict: 'E',
templateUrl: '/Scripts/app/directives/myDirective.html'
};
}
);
I would like to use the directive as shown below:
<my-directive my-value="{{dataFromScope}}"></my-directive>
i.e. I want to use the evaluated dataFromScope
value inside my custom directive as dataFromRootScope
. How can I reach this?
答案 0 :(得分:2)
You can use isolated scope two-way binding:
dirModule.directive('myDirective', function() {
return {
scope: {
model: '=myValue'
},
restrict: 'E',
templateUrl: '/Scripts/app/directives/myDirective.html'
};
});
Where directive template is
<div>
<input ng-model="model" />
</div>
and usage is
<my-directive my-value="dataFromScope"></my-directive>
答案 1 :(得分:2)
我想在自定义中使用评估的dataFromScope值 指令为dataFromRootScope。我怎么能达到这个目标?
你有两种选择来实现这一目标。
选项-1 :为您的指令创建一个独立的范围
这样,您需要从myValue指定dataFromRootScope
的值。 =
运算符可确保双向绑定。
app.directive('myDirective', function() {
return {
restrict: 'E',
scope:{
dataFromRootScope: '=myValue'
},
templateUrl: 'myDirective.html'
};
}
);
&#39; dataFromScope&#39;将无法在myDirective中使用,因为它具有隔离范围。您可以通过dataFromRootScope
访问它(请参阅如何从myValue
获取其价值)
<div>
<input value="{{dataFromRootScope}}" />
</div>
选项-2 :享受共享范围。
在这种情况下,您不需要创建隔离范围。您只需在指令模板中使用dataFromScope
,或者如果您真的想在模板中以dataFromRootScope
的形式访问它,只需在链接函数中指定它即可。
app.directive('myDirective', function() {
return {
restrict: 'E',
templateUrl: 'myDirective.html',
link:function(scope,ele,attr){
scope.dataFromRootScope = scope.dataFromScope
}
};
}
);
<div>
<input value="{{dataFromRootScope}}" />
</div>
答案 2 :(得分:1)
You can use the '@' sign :
dirModule.directive('myDirective', function() {
return {
scope: { myValue: '@' },
restrict: 'E',
templateUrl: '/Scripts/app/directives/myDirective.html'
};
});
The '@' sign binds the evaluated value of the DOM attribute to the directive.
You can then use the directive as you asked :
<my-directive my-value="{{dataFromScope}}"></my-directive>