How to Get Html Element Attributes in AngularJS?


Edit: Everyone went on all kinds of tangents, but the question remains - how do I get an attribute of an html element inside an angular controller?

Here is a plnkr attempt:

    //$scope.myElem = angular.element('testDiv'); //this breaks angular
    $scope.myElem = $document.find('testDiv'); //this doesn't break angular, but unclear what it returns
    $scope.myAttr = $; //this returns nothing

If you need convincing that this is actually necessary - I need to find when a user scrolls through a div, as is shown here: Note that this has nothing to do with the question, simply a scenario. The question is simple - how do I get an attribute's value?

Useless official docs:
The only useful link that still doesn't work:

Problem courtesy of: VSO


You could use the element api

There should be only very few occasions where you would really need it, though.

Solution courtesy of: Julia Will


Use angular.element:

var myElem = angular.element("#testDiv"); // here you get your div
var myAttr = myElem.attr("name"); // you get: "testDiv"

Remember you have limitations using jqlite. If you want full functionallity of jquery element, import a full "jquery.js" before importing your angular script.

However, to manipulate the DOM you SHOULD use directives as stated by most of the answers.

Discussion courtesy of: Cyberdelphos

You should manipulate the DOM using directives. The controller should only manipulate the data of the application and offer it to the html.

If you have direct manipulation on the Controller you can't, for example, bind several views to the controller. Also, if you change the id of one tag in the html and you are manipuling it directly in you controller, the controller will break.

Read this:

Hope it helps.

Discussion courtesy of: Juan Marcos Armella

This recipe can be found in it's original form on Stack Over Flow.