我有两个这样的元素:
<div ng-hide="showDiv"></div>
<div ng-show="showDiv">
<div directive></div>
</div>
这样的指令:
app.directive ('directive', [
...
controller: [
'$scope',
function ($scope) {
$scope.accept = function () {
$scope.showDiv = false;
};
}
],
....
]
我试图在指令中使用$ scope.showDiv切换控制器,但它没有用。如何在指令中访问控制器的范围?
指令中的console.log($ scope)显示$ scope.showDiv === false,但控制器中的$ scope.showDiv ===是。
答案 0 :(得分:1)
如果使用controllerAs
语法,则可以简单地实现此目的。
HTML
<div ng-hide="showDiv"></div>
<div ng-show="showDiv">
<div dir-show-div is-shown="showDiv"></div>
</div>
指令
angular
.module('app')
.directive('dirShowDiv', dirShowDiv);
function dirShowDiv() {
var directive = {};
directive.scope = {
isShown: '='
};
directive.controller = 'DirController';
directive.controllerAs = 'vm';
return directive;
}
指令控制器
angular
.module('app')
.controller('DirController', DirController);
function DirController() {
var self = this;
self.accept = accept;
function accept() {
self.isShown = false;
}
}
答案 1 :(得分:0)
$scope.showDiv = true
是原始值,不会被指令的范围继承。将值赋给对象允许指令的作用域继承该对象,并且指令作用域中的任何更改都将传递回父作用域。
//controller
//change primitive to object
$scope.showDiv = {status: true};
//template
//directive names in HTML are usually in kebab case but i'm keeping it obvious for now.
//Pass showDiv object to directive
<div ng-show="showDiv.status">
<div directive showDiv="showDiv"></div>
</div>
//directive
app.directive ('directive', [
...
return {
scope : {
//bind directive scope to parent
showDiv: '=showDiv'
}
controller: [
'$scope',
function ($scope) {
$scope.foo = function () {
//Changing object in directive will also update parent scope.
$scope.showDiv.status = false;
};
}
],
....
]
//controller
//after $scope.foo executed in directive
console.log(showDiv) === {status: false}