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/
You can use document. getElementById() in Angularjs, but manipulating HTML in a controller is not a good practice.
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.
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.
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 }
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With