I am trying to create a custom event for toggling with Angular. The directive is called toggleable.
It sounds trivial at first, but tricky bit is that i want to be able to to use any button or link on the page for toggling.
The code i have written is as below
Directive
'use strict';
angular.module('onsComponents')
.directive('togglable', function() {
return {
restrict: 'A',
transclude: true,
scope: {
togglerId: '@',
show: '@'
},
link: function(scope, element, attrs) {
if (!scope.togglerId) {
console.error("Toggler id must be given")
return
}
scope.visible = (scope.show === 'true')
scope.toggle = function() {
alert("Before " + scope.visible)
scope.visible = !scope.visible
alert("After " + scope.visible)
}
//Bind click event to given dom element
angular.element('#' + scope.togglerId).bind("click", function() {
scope.toggle()
})
},
templateUrl: 'app/components/toggler/toggler.html'
}
})
The Template
<div ng-transclude ng-show="visible">
</div>
The View
<a href="" id="toggleButton" >Click me to toggle</a>
<div togglable toggler-id="toggleButton">
Hey
</div>
The toggle link seems to be working. I can see the alerts when the link is clicked. The trouble is the content does not appear. It seems like the link is not really is in the same scope with the content, another scope is created when i do this.
If i move the click link within the template as below, it works. But that is not really what i want.
<!-- Move the link inside template -->
<a href="" ng-click="toggle()" >Click me to toggle</a>
<div ng-transclude ng-show="visible">
</div>
So how can i achieve that ?