父控制器的范围在您的指令中可用,即使您已通过$parent
指令范围上的属性隔离了范围。
app.directive('myDir', function() {
return {
restrict: 'A',
scope: {},
link: function(scope, element, attrs) {
scope.isOpen = false;
scope.$parent.whatever; //this came from your containing controller.
}
}
});
不过要小心……以这种方式紧密耦合指令和控制器变得非常容易。在大多数情况下,最好将作用域的属性与标记中的作用域声明和属性链接起来,如下所示:
指令:
app.directive('myDir', function() {
return {
restrict: 'A',
scope: {
propFromParent: '=prop',
funcFromParent: '&func'
},
link: function(scope, element, attrs) {
scope.isOpen = false;
scope.$parent.whatever; //this came from your containing controller.
}
}
});
标记:
<my-dir prop="foo" func="bar()"></my-dir>
你的控制器:
app.controller('SomeCtrl', function($scope) {
$scope.foo = 'test';
$scope.bar = function() {
$scope.foo += '!';
};
});