有人可以帮忙解决这个问题吗?有没有办法访问指令所在的范围(例如 Controller 的范围),同时我仍然可以访问属性的值。
这是我的指令代码
app.controller("someCtr", function( $scope ){
$scope.controllerScopeVariable = "Lorem";
});
app.directive('myDirective', [function () {
return {
restrict: 'A',
scope: {
directiveAttributeValue: "="
},
link: function (scope, element, attrs) {
var bar = scope['directiveAttributeValue'];
var foo = scope['controllerScopeVariable']; //I need to access this
}
};
}]);
这是 HTML:
<div ng-controller="someCtr">
<div myDirective directiveAttributeValue="{{blabla}}">
</div>
</div>
在指令中,我无法访问范围['controllerScopeVariable']。我怎样才能做到这一点?
最佳答案
您还必须在指令的 scope
属性中定义变量 controllerScopeVariable
。
例如:
app.controller("someCtr", function( $scope ){
$scope.controllerScopeVariable = "Lorem";
});
app.directive('myDirective', [function () {
return {
restrict: 'A',
scope: {
directiveAttributeValue: "=",
controllerScopeVariable: "&"
},
link: function (scope, element, attrs) {
var bar = scope['directiveAttributeValue'];
var foo = scope['controllerScopeVariable'];
}
};
}]);
请记住,可以通过三种方法来定义可以传递的本地范围属性:
- @ 用于将字符串值传递到指令中
- = 用于创建到传递到指令的对象的双向绑定(bind)
- & 允许将外部函数传递到指令中并调用
关于javascript - AngularJS:如何继承指令所在的范围,并同时获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26239982/