我的视图中有一个按钮,它完全在视图中处理,因为它只是一个简单的开关,用ng-show指令切换元素的视图。我希望能够从指令内部切换视图。
这是我要做的事情的示例代码:
<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 ???
},
...
};
});
答案 0 :(得分:2)
在angular指令中,您可以访问父作用域或隔离作用域。如果您打算使用父范围,那么
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;
});
详细了解角度范围here
答案 1 :(得分:0)
var app = angular.module("test",[]);
app.directive("myDirective",function(){
return {
restrict: "EA",
scope: true,
link: function(scope,elem,attr){
// code goes here ...
}
}
});
答案 2 :(得分:0)
您可以直接访问指令中的父范围变量。
angular.module('your-module').directive('myDirective', function() {
return {
controller: function ($scope) {
$scope.ToChange = !$scope.ToChange;
}
};
});