Angular custom directive: Access parent scope property in linking function
I want to set the name of an event (click or touch) on a parent scope in
angular as a string. On a child scope I want to use that string to bind an
event with element.on.
Example:
angular.module('directives', [])
.directive('Sidebar', function () {
'use strict';
return {
link: function (scope) {
//determines whether or not to use click or touch events
//I want to use this to bind events with
//element.on(scope.sidebarClickEvent) in child scopes
scope.sidebarClickEvent = 'click';
},
restrict: 'E',
templateUrl: 'sidebar.html'
};
})
.directive('collapseBtn', function() {
'use strict';
return function (scope, element) {
element.on(scope.sidebarClickEvent /* undefined */ , function
() {
//scope.sidebarClickEvent is available here, when the
event handler executes
scope.toggleSidebarCollapseState();
element.find('i').toggleClass('icon-double-angle-right');
});
};
})
The problem is that properties defined on the parent scope aren't
available when I bind the events, so scope.sidebarClickEvent is undefined
when I bind the event. But if I change it to a regular click event then I
can get the property in the event handler.
Can I access properties inherited by the scope at the time that the event
binding occurs? I'm not even sure that I'm understanding scope inheritance
properly here, so pointing out errors in my understanding would also be
appreciated.
Thanks.
No comments:
Post a Comment