6

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
  • 2,342
  • 4
  • 28
  • 36
  • You can use jqlite provided by angularjs which is an alternative for jQuery in angular realm, however you might want to do this in some other way reading data from HTML is not angular way you want to make the model do it except when you're dealing with directives. – Ashish Gaur Apr 07 '15 at 07:08

2 Answers2

16

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>
Michael Kang
  • 52,003
  • 16
  • 103
  • 135
  • for me $attrs are undefined, do you have any working fiddle to show? – Kania Apr 07 '15 at 07:33
  • You'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. – Sean_A91 Apr 29 '16 at 14:08
0

In Angular world you should use directives to manipulate with DOM elements. Here a nice explanation how to get attribute value from custom directive (How to get evaluated attributes inside a custom directive).

But if you still want to get it's value from controller you are able to use jQuery as well $('#project_configuration').data('project-id')

Community
  • 1
  • 1
Ivan Burnaev
  • 2,690
  • 18
  • 27
  • 3
    It is not a good practice to use jquery from inside your controller. Directive is the best place to use jquery. – ATHER May 25 '16 at 22:24