Angularjs: how to find an element based on a data-attribute value?

rnrneverdies picture rnrneverdies · Sep 8, 2014 · Viewed 14.4k times · Source

I've got the following directive:

template: '<div data-div="outer"><div data-div="inner"></div></div>',
link: function postLink(scope, elem, attrs) {
       var outer = elem.find('[data-div="outer"]');
       var inner = elem.find('[data-div="inner"]');
       outer.css({
           'background': 'red',
           'width': "100%",
           'height': "100%",
       });
       inner.css({
           'background': 'blue',
           'width': "50%",
           'height': "100%",
       });
    }

Based on this post, i tried these selectors. but im using jQLite, not JQuery.

so, how to find an element based on a data-attribute value?

http://plnkr.co/edit/FeJWvwnKjOZwAIABigtA?p=preview

Answer

Anthony Chu picture Anthony Chu · Sep 8, 2014

You can use querySelector() (or querySelectorAll() for multiples) to get a similar find() behavior when using jqLite...

function postLink(scope, elem, attrs) {
    var outer = angular.element(elem[0].querySelector('[data-div="outer"]'));
    var inner = angular.element(elem[0].querySelector('[data-div="inner"]'));
    outer.css({
       'background': 'red',
       'width': "100%",
       'height': "100%",
    });
    inner.css({
       'background': 'blue',
       'width': "50%",
       'height': "100%",
    });
}