One solution, which I particularly prefer, is to use a function existing only in the scope of the directive, so you don’t need to do "some fix", "hacks" or worse, depend on a function of a controller
- that goes completely against the purpose of a directive
.
Just make a definition of a function within the directive and assign to the element through a ngClick
, see:
.directive('acao', function() {
return {
restrict: 'A',
link: function(scope, element, attr) {
scope.meuClick = function() {
console.log('rodou');
}
}
};
});
And in your html:
<ul acao>
<li ng-repeat="item in items" ng-click="meuClick()"></li> //ngRepeat somente de exemplo
</ul>
Why use this template?
You have greater control and better maintenance over the code. Imagine that in the future you need to change the structure from ul/li to div/span, for example, or you need to change the location where the directive is set. This way you don’t need to review the entire code structure in Directive, check if it needs a new find, etc..
You apply the click directly on the element you need and only within the scope of the directive, which does not interfere with others.
That’s jQuery, isn’t it? What version? The
bind
is already out of date.– bfavaretto
It’s not jquery! $element is a variable I create in the directive link, I just put its $element name.
– Hiago Souza
But angular uses jqLite, nay?
– bfavaretto
On the Angular website it says . bind is from jqLite, but this in the angular documentation.
– Hiago Souza
That, uses jqLite is what I’ve seen now. But anyway because it can’t navigate between the elements that way?
– Hiago Souza
Seems to be a limited find. Just tried
$element.find("li").bind(...)
?– bfavaretto
It does not meet with find('li'), now if I use it outside the directive link it works ( agular.element('body'). find('ul li') )
– Hiago Souza
If you put the
bind
in the<ul>
and it works, it’s probably because the<li>
not created yet. Or they are recreated later. It is better to leave in the<ul>
. You can take the clicked element the same way (usefunction(e) { var clicado = e.target; /* etc */ }
in the bind).– bfavaretto
It makes sense, the li is an ng-repeat.
– Hiago Souza
angular does not work using Sizzle.
– Luan Fagundes
Sync and corrections by n17t01 ?
– Hiago Souza