8

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!

user2871401
  • 1,867
  • 5
  • 22
  • 24
  • 1
    AngularJS doesn't do this. jQuery does this. Load jQuery in your application and it should work – Abilash Dec 17 '13 at 14:22
  • 2
    That's not entirely true: you can do this with custom directives, which would be the "Angular" way of doing things. Can you post a bit more information about your use case? – Michal Charemza Dec 17 '13 at 14:24
  • 1
    A golden rule of Angular development is to never, ever touch the DOM from the controller. So to answer your question with a few questions: Where are you placing this javascript code, and what are you planning to do with these elements? If this code goes anywhere else than in a custom directive, you may want to step back and think about doing this another way. – MW. Dec 17 '13 at 14:27

2 Answers2

6

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'))
Atropo
  • 12,231
  • 6
  • 49
  • 62
1

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.

Shiva127
  • 2,413
  • 1
  • 23
  • 27
Rama Krishna
  • 85
  • 1
  • 8