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...

1
  • 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. Commented Apr 7, 2015 at 7:08

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

for me $attrs are undefined, do you have any working fiddle to show?
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.
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')

1 Comment

It is not a good practice to use jquery from inside your controller. Directive is the best place to use jquery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.