本质上,我希望能够访问我创建的指令的父范围,但我也希望能够访问我放置在元素上的属性。
例如相关js
app.directive('testDirective', function(){
return {
restrict:"E",
templateUrl:"directive.html",
scope:{
testAttribute: '='
}
};
});
app.controller('mainCtrl', function($scope){
$scope.name = 'henry'
}
index.html
<div ng-controller="mainCtrl">
<test-directive test-attribute="Hello"></test-directive>
</div>
指令.html
{{testAttribute}}
{{name}}
输出是“Hello”而不是“Hello Henry”
所以澄清一下,我想要做的就是访问属性和父范围。
最佳答案
对于您想要做的事情,不需要双向绑定(bind)。您正在尝试访问指定为属性的文本。您可以将指令写为:-
.directive('testDirective', function(){
return {
restrict:"E",
//scope:true, //apply if required
templateUrl:"directive.html",
link:function(scope, elm, attrs){
scope.testAttribute = attrs.testAttribute; //Get it from attributes
}
};
});
<强> Demo
现在指令设置的作用域属性将使用父作用域本身。但理想的情况下,您可能希望使用 scope:true
(父级的子级范围)或具有隔离范围的 2 路绑定(bind)
。但此时,由于不太确定您最初的目标是什么,这是一个基于您的问题的解决方案。
总结一下:-
I want to be able to access the parent scope of the directive I have created
删除隔离范围并仅使用父级范围。
but I also want to be able to access the attributes that I have placed onto the element.
使用链接函数的attrs
参数(attrs.testAttribute
)。如果您想将其评估为绑定(bind)值,请执行 (scope.$eval(attrs.testAttribute)
)
关于javascript - 如何从自定义指令访问元素属性,同时保持对父范围的访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26199011/