我的 View 中有一个按钮,它完全在 View 中处理,因为它只是一个使用 ng-show 指令切换元素 View 的简单开关。我希望能够从指令内部切换 View 。
这是我正在尝试执行的示例代码:
<div>
<button ng-click="ToChange=true">
<my-directive ng-show="ToChange"></my-directive>
</div>
.directive('myDirective', function() {
return {
...
controller: function ($scope) {
$scope.whenClickedThis = $scope.ToChange=false ???
},
...
};
});
最佳答案
在您的 Angular Directive(指令)中,您可以访问父范围或隔离范围。如果您计划使用父作用域,那么
angular.module('app')
.controller('mainController', function($scope){
$scope.ToChange = false;
})
.directive('myDirective', function(){
return {
restrict: 'E',
controller: function($scope){
//You can access $scope.ToChange here
}),
link : function($scope, $element, $attribute){
//You can access $scope.ToChange here
}
}
});
<div ng-controller="mainController">
<button ng-click="ToChange=true">
<my-directive ng-show="ToChange"></my-directive>
</div>
如果您计划为指令创建隔离范围,
angular.module('app')
.controller('mainController', function($scope){
$scope.ToChange = false;
})
.directive('myDirective', function(){
return {
restrict: 'E',
scope : {
change : '='
},
controller: function($scope){
//Now you can access $scope.change from here
}),
link : function($scope, $element, $attribute){
//Now you can access $scope.change from here
}
}
});
<div ng-controller="mainController">
<button ng-click="ToChange=true">
<my-directive change="ToChange"></my-directive>
</div>
如果您想识别变量的任何更改,可以在指令中创建监视
$scope.$watch('change', function(oldValue, newValue) {
//Do something here;
});
了解有关 Angular 范围的更多信息 here
关于javascript - 如何从内部指令更改 Controller 的 $scope 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44540009/