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

I am still struggling with simple things in Angular. I have jQuery and Backbonejs backgrounds, so please don't yell at me. I try to understand the differences.

I have HTML in which from rails the project identifier is set as data-project-id:

<div data-ng-controller="ProjectCtrl as ctrl" data-project-id="1" id="project_configuration"> 

Is there a chance to access this attribute? I need this for my API calls ...

+6
source share
2 answers

To access element attributes from a controller, enter $attrs in 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> 
+15
source

In the Angular world, you should use directives to control DOM elements. Here's a good explanation of how to get the attribute value from a custom directive ( How to get evaluated attributes inside a custom directive ).

But if you still want to get this value from the controller, you can also use jQuery $('#project_configuration').data('project-id')

0
source

Source: https://habr.com/ru/post/984771/


All Articles