Reputation: 23
I am attempting to build a simple show/hide directive based on elements transcluded into divs. I have a parent and a child directive. When the parent directive is clicked on, the child directive should toggle show/hide it's div. The toggle function sits in the parent controller and toggles the variable between true and false so that the child directive can show/hide.
The problem: the toggle function in the parent directive works correctly, however the child directive is not aware of the toggle variable changing when the parent is clicked. I am passing the ctrl to the link function in the child directive by using require. This way I can access the parent controller objects for showing and hiding. The toggle variable is visible by the child, but does not reflect any changes after the initial load of the page. When clicked, nothing shows or hides.
code:
angular.module('demo', [])
.directive('demoParent', function() {
return {
restrict: 'E',
scope: {},
transclude: true,
template: '<div ng-click="toggleTarget()" ng-transclude></div>',
controller: function($scope) {
$scope.toggleTarget = function() {
this.openTarget = !this.openTarget;
};
this.openTarget = false;
}
};
})
.directive('demoChild', function() {
return {
require: '^demoParent',
restrict: 'E',
transclude: true,
link: function(scope, elem, attrs, ctrl) {
scope.ctrl = ctrl;
},
template: '<div ng-show="ctrl.openTarget" ng-transclude></div>',
};
});
Does the child need to add a watcher to the parent ctrl or is this a case of isolated variables once passed from parent to child?
Upvotes: 2
Views: 608
Reputation: 17064
I've made a Fiddle with your working scenario, you had an issue with the this
functionality as well, except the ^demoChild
which you said was a typo. Once inside your function, the this
was pointing to the scope, and not the controller as you expected, so this section should be amended:
controller: function($scope) {
this.openTarget = false;
var _ctrl = this;
$scope.toggleTarget = function() {
_ctrl.openTarget = !_ctrl.openTarget;
};
}
Upvotes: 1
Reputation: 3823
try this: var me = this; $scope.toggleTarget = function() { me.openTarget = !me.openTarget; };
Upvotes: 0