Angularjs |如何从元素的属性值,在其控制的定义 [英] Angularjs | how to get an attribute value from element in which controller is defined

查看:194
本文介绍了Angularjs |如何从元素的属性值,在其控制的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然在角简单的事情的战斗。我有jQuery和Backbonejs背景,所以请不要对我大喊大叫。我努力尝试理解差异

我的HTML从铁轨被赋予项目数据项目的编号,编号:

 < D​​IV数据-NG-控制器=ProjectCtrl作为CTRL数据项目-ID =1ID =project_configuration>

有没有机会去访问这个属性?我需要它我的API调用...


解决方案

要访问的元素从控制器属性,注入 $ ATTRS 到您的控制器功能:

HTML

 < D​​IV测试=Hello World的NG-控制器=CTRL>
< / DIV>

剧本

  app.controller(Ctrl键,功能($ ATTRS){
  警报($ attrs.test); //警报世界你好
});

在你的榜样,如果你想获得的数据项目编号:

  $ attrs.projectId

或者,如果你想获得ID:

  $ attrs.id

演示:

\r
\r

VAR应用= angular.module('应用',[]);\r
app.controller('CTRL',函数($ ATTRS){\r
  警报($ attrs.test);\r
});

\r

&LT;脚本SRC =htt​​ps://ajax.googleapis.com/ajax /libs/angularjs/1.2.23/angular.min.js\"></script>\r
&LT; D​​IV NG-应用=应用程序NG控制器=CTRL测试=Hello World的&GT;\r
  \r
&LT; / DIV&GT;

\r

\r
\r

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

解决方案

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>

这篇关于Angularjs |如何从元素的属性值,在其控制的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆