Reputation: 7078
I'm trying to create a simple directive to avoid having bulky elements for hovering. This is what I have:
app.directive('ngHover', function(){
return {
compile: function($element,attr) {
$element.attr('ng-mouseenter',attr.ngHover + ' = true')
.attr('ng-mouseleave',attr.ngHover + ' = false')
.removeAttr('ng-hover');
}
}
})
The resulting element is what I would have wrote (and would have worked) but it doesn't seem to be added before angular uses $compile
. I could use $compile
manually but I want to understand why this doesn't work.
Upvotes: 0
Views: 70
Reputation: 1386
This is how the compiler of Angular works.
Compiler is an Angular service which traverses the DOM looking for attributes. The compilation process happens in two phases.
Compile: traverse the DOM and collect all of the directives. The result is a linking function.
Link: combine the directives with a scope and produce a live view...
Which means that by the time when you are inside of compile function where you add the attributes, it's over and compiler will never discover and recognise ng-mouseenter
and ng-mouseleave
as directives. In order to achieve this you will need to trigger another round of compilation with $compile
, as you said.
Also see this message and the whole thread. There you can see that it would work if you were setting extra directives on children of the current element, but not on itself.
Upvotes: 1