Alex Rivera | Logout

AngularJS accessing DOM elements inside directive template

Asked 2013-04-08T14:14:52.683
68

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?

Edit
Report

1 Answer

48

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]),
        // ...
    }
}
answered 2013-04-08T14:40:00.217

Your Answer