Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Find Element by Attribute Value

Tags:

dom

angularjs

I'm trying to use AngularJS to query the DOM of my view. I need to get all of the elements that have the attribute 'data-placement' with the value of 'top'. In jQuery, I would do this:

var elements = $('[data-placement="top"]');

However, I don't know how to do it with AngularJS. Can someone tell me how to do this?

Thank you!

like image 289
user2871401 Avatar asked Dec 17 '13 14:12

user2871401


2 Answers

In AngularJS you won't do direct DOM manipulation from the controller, you should create a directive to to that. Inside the directive you can use JQuery as you wish.

Anyway you I think you can use angular.element() with a JQlite selector, here's the documentation of angular.element.

Example:

// find('#id')
angular.element(document.querySelector('#id'))
like image 155
Atropo Avatar answered Sep 19 '22 19:09

Atropo


From your question I understand that you wanted to find elements with atrributes requiring certain condition in that case we can use $document.

You can find more info about it here.

So coming to your requirement, you can find it by.

$document.find("[attribute-name='attribute-value')");

That will return the element object wrapped in jQuery or jqLite. But to use it you need to inject $document into your controller. So you continue angular related operations with it.

Another approach to this is angular.element.

angular.element.find("[attribute-name='attribute-value')");

But this will return element with wrapped raw DOM element or HTML string as a jQuery element. you can find more info about it here

I prefer to use $document as Angular operations can be done using the first method.

like image 36
Rama Krishna Avatar answered Sep 18 '22 19:09

Rama Krishna