I have a simple Angular directive that adds a CSS class to an element when being clicked:
.directive("addClass", function () {
return {
scope: {
name: "=addClass"
},
link: function (scope, element, attributes) {
element.on("click", function () {
element.addClass(scope.name);
console.log("Element activated");
});
element.on("mouseleave", function () {
element.removeClass(scope.name);
console.log("Element deactivated");
});
}
}
});
I'm using it on my links:
<a href="" add-class="class-name">...</a>
But when I click my link my event handlers execute, although scope.name is undefined. I could read attribute value using attributes, but that beats the purpose of assigning attribute values to scope properties as described in Angular Directives API.
What am I doing wrong?
ng-clickthen handleclickevent directly. Otherwise, you will need to let Angular know (if you want to manipulate the scope) that you are listening to the DOM by callingscope.$apply.$apply()is required here since he's handling the element directly (no digest cycle involved). Besides, his directive seems to be used along with another element, so a custom template couldn't be used.