Reputation: 658
I have a button inside my view, which is handled entirely in the view, since its only a simple switch to toggle the view of an element with ng-show directive. I want to be able to toggle the view from inside the directive it self though.
Here an example code of what am trying to do:
<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 ???
},
...
};
});
Upvotes: 0
Views: 90
Reputation: 407
You can directly access parent scope variable in your directive.
angular.module('your-module').directive('myDirective', function() {
return {
controller: function ($scope) {
$scope.ToChange = !$scope.ToChange;
}
};
});
Upvotes: 0
Reputation: 407
In your angular directive, you can have either access parent scope or isolate scope. If you are planning to use parent scope, then
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>
If you are planning to create an isolate scope for your directive,
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>
You can create a watch in your directive if you want to identify any changes to your variable
$scope.$watch('change', function(oldValue, newValue) {
//Do something here;
});
Read more about angular scope here
Upvotes: 2
Reputation: 1
var app = angular.module("test",[]);
app.directive("myDirective",function(){
return {
restrict: "EA",
scope: true,
link: function(scope,elem,attr){
// code goes here ...
}
}
});
Upvotes: 0