Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs | how to get an attribute value from element in which controller is defined

Tags:

dom

angularjs

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

like image 243
Kania Avatar asked Apr 07 '15 07:04

Kania


People also ask

How can you retrieve the value of an element's attribute?

The getAttribute() method of the Element interface returns the value of a specified attribute on the element.

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods. The scope($) acts as a link between controller and view.

What are the AngularJS controllers?

The controller in AngularJS is a JavaScript function that maintains the application data and behavior using $scope object. You can attach properties and methods to the $scope object inside a controller function, which in turn will add/update the data and attach behaviours to HTML elements.

What does $compile do in AngularJS?

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.


Video Answer


1 Answers

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>
like image 144
pixelbits Avatar answered Oct 09 '22 04:10

pixelbits