Is there a more "angular" way of selecting DOM elements inside a directive template? For example, say you have this directive:
app.directive("myDirective", function() {
return {
template: '<div><ul><li ng-repeat="item in items"></ul></div>',
link: function(scope, element, attrs) {
var list = element.find("ul");
}
}
});
I used the jQuery style selector to get a hold of the DOM <ul>
element rendered in my template. Is there a better way to do this?
This question is related to
angularjs
angularjs-directive
This answer comes a little bit late, but I just was in a similar need.
Observing the comments written by @ganaraj in the question, One use case I was in the need of is, passing a classname via a directive attribute to be added to a ng-repeat li tag in the template.
For example, use the directive like this:
<my-directive class2add="special-class" />
And get the following html:
<div>
<ul>
<li class="special-class">Item 1</li>
<li class="special-class">Item 2</li>
</ul>
</div>
The solution found here applied with templateUrl, would be:
app.directive("myDirective", function() {
return {
template: function(element, attrs){
return '<div><ul><li ng-repeat="item in items" class="'+attrs.class2add+'"></ul></div>';
},
link: function(scope, element, attrs) {
var list = element.find("ul");
}
}
});
Just tried it successfully with AngularJS 1.4.9.
Hope it helps.
I don't think there is a more "angular way" to select an element. See, for instance, the way they are achieving this goal in the last example of this old documentation page:
{
template: '<div>' +
'<div class="title">{{title}}</div>' +
'<div class="body" ng-transclude></div>' +
'</div>',
link: function(scope, element, attrs) {
// Title element
var title = angular.element(element.children()[0]),
// ...
}
}
Source: Stackoverflow.com