Angularjs | how to get an attribute value from element in which controller is defined
28,228
To access an elements attributes from a controller, inject $attrs
into your controller function:
HTML
<div test="hello world" ng-controller="ctrl">
</div>
Script
app.controller('ctrl', function($attrs) {
alert($attrs.test); // alerts 'hello world'
});
In your example, if you want to get data-project-id:
$attrs.projectId
Or if you want to get id:
$attrs.id
Demo:
var app = angular.module('app',[]);
app.controller('ctrl', function($attrs) {
alert($attrs.test);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl" test="hello world">
</div>
Author by
Kania
Updated on April 07, 2020Comments
-
Kania about 4 years
I'm still fighting with simple things in Angular. I have jQuery and Backbonejs background, so please do not yell on me. I try hard to understand differences
I have HTML in which from rails is given ID of project as data-project-id:
<div data-ng-controller="ProjectCtrl as ctrl" data-project-id="1" id="project_configuration">
Is there any chance to get access to this attribute? I need it to my API calls...
-
Kania about 9 yearsfor me $attrs are undefined, do you have any working fiddle to show?
-
Sean_A91 about 8 yearsYou're assuming they are working with a custom directive. This would probably be why $attrs is undefined. since they may just be in a view's controller instead of a directive's controller.
-
ATHER about 8 yearsIt is not a good practice to use jquery from inside your controller. Directive is the best place to use jquery.