I was having doubts about how to implement a custom event in Angular, so I though, "wait, why not check the Angular default events directives, like ng-click, etc"?
So I found this here.
And here are the relevant bits:
['$parse', function($parse) {
return {
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}
};
}];
That's how each event directive is declared. Using the compile
method.
But here I have my doubts. Why 2 different $element
and element
, in what situation those two are going to differ? Why use the compile
method, if you can just use link
? Why $parse
if you can $eval
?
I mean, I would just do something like:
function() {
return {
link: function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
scope.$eval(attr[directiveName], {$event: event});
});
};
}
};
};
What are the advantages/differences of the Angular approach, vs my approach?