如何使用AngularJS获取元素的属性 [英] How to get an element's attribute with AngularJS

查看:31
本文介绍了如何使用AngularJS获取元素的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

<div class="col-md-10" data-ng-controller="type-controller">
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-success" ng-model="typeId" data-btn-radio="'1'">
            Option 1
        </label>
        <label class="btn btn-success" ng-model="typeId" data-btn-radio="'2'">
            Option 2
        </label>
    </div>
    <input data-ng-model="typeId" name="typeId" type="hidden" data-start="2" />
</div>

我的 type-controller 为空,因此我省略了它-但我想从类型控制器.

My type-controller is empty so I'm omitting it - but I want to get the value of the attribute data-start from the last input inside the type-controller.

我没有使用jQuery.

I'm not using jQuery.

推荐答案

如果属性 data-start 很重要,因为其他第三方库正在使用它,那么您可以考虑简单地使用在服务器上创建 ng-init

IF the attribute data-start is significant because it is being used by some other 3rd party library, then you might consider simply using ng-init when you create this on the server:

<input data-ng-model="typeId" name="typeId" type="hidden" data-start="2" 
 ng-init='start = 2' />

这实际上将运行您需要的任何代码,并且无需您从DOM中解析出数据属性.

This will essentially run any code you need, and doesn't involve you having to parse out data attributes from the DOM.

您可以编写一个简单的指令以提取值并使用表达式进行发布.这基本上可以完成同样的事情,但是我认为更加困难:

You could write a pretty trivial directive to pull in the value and publish using an expression. This will essentially accomplish the same thing, but is more difficult in my opinion:

angular.module('data-pluck', [])
  .controller('fooController', function() {

    this.name = 'Foo Controller';

  })
  .directive('pluckData', ['$parse',
    function($parse) {

      return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
          var expression = function() {};
          expression.assign = function() {};

          scope.$watch(attrs.placeData, function() {
            expression = $parse(attrs.placeData);
          });

          scope.$watch(attrs.pluckData, function() {
            expression.assign(scope, attrs[attrs.pluckData]);
          });
        }
      };

    }
  ]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='data-pluck' ng-controller='fooController as ctrl'>
  <h1>{{ctrl.name}}</h1>
  <div data-my-val="I'm value one" pluck-data='myVal' place-data='ctrl.valueOne'>
    <p>I'm a regular old <code>&lt;p&gt;</code> tag</p>
    <input type='hidden' data-my-val="I'm the second value" pluck-data='myVal' place-data='ctrl.valueTwo' />
  </div>
  <h3>These Values Populated Dynamically</h3>
  <ul>
    <li>ctrl.valueOne = {{ctrl.valueOne}}</li>
    <li>ctrl.valueTwo = {{ctrl.valueTwo}}</li>
  </ul>
</div>

这篇关于如何使用AngularJS获取元素的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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