Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - get element attributes values

How do you get an element attribute value?

e.g. HTML element:

<button data-id="345" ng-click="doStuff($element.target)">Button</button> 

JS:

function doStuff(item){     angular.element(item)[0].data('id'); // undefined is not a function } 

Any suggestions much appreciated, JSFIDDLE demo here:http://jsfiddle.net/h3TFy/

like image 879
Iladarsda Avatar asked Jul 10 '14 09:07

Iladarsda


People also ask

Can we use document getElementById in AngularJS?

You can use document. getElementById() in Angularjs, but manipulating HTML in a controller is not a good practice.

What is $element in AngularJS?

The angular. element() Function in AngularJS is used to initialize DOM element or HTML string as an jQuery element. If jQuery is available angular. element can be either used as an alias for the jQuery function or it can be used as a function to wrap the element or string in Angular's jqlite.

What is angular jqLite?

jqLite is a tiny, API-compatible subset of jQuery that allows AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most commonly needed functionality with the goal of having a very small footprint. To use jQuery , simply ensure it is loaded before the angular. js file.


2 Answers

Since you are sending the target element to your function, you could do this to get the id:

function doStuff(item){     var id = item.attributes['data-id'].value; // 345 } 
like image 175
rob Avatar answered Sep 23 '22 04:09

rob


You just can use doStuff($event) in your markup and get the data-attribute values via currentTarget.getAttribute("data-id")) in angular. HTML:

<div ng-controller="TestCtrl">     <button data-id="345" ng-click="doStuff($event)">Button</button> </div> 

JS:

var app = angular.module("app", []); app.controller("TestCtrl", function ($scope) {     $scope.doStuff = function (item) {         console.log(item.currentTarget);         console.log(item.currentTarget.getAttribute("data-id"));     }; }); 

Forked your initial jsfiddle: http://jsfiddle.net/9mmd1zht/116/

like image 26
andreaslangsays Avatar answered Sep 22 '22 04:09

andreaslangsays