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!

3
  • 1
    AngularJS doesn't do this. jQuery does this. Load jQuery in your application and it should work Commented Dec 17, 2013 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? Commented Dec 17, 2013 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. Commented Dec 17, 2013 at 14:27

2 Answers 2

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'))
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.