javascript 使用 AngularJS 获取属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31334869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:40:15  来源:igfitidea点击:

getAttribute value with AngularJS

javascriptangularjs

提问by Darren Sweeney

I have the following controller... I'm trying to get the nameand ratingattibute from an HTML input, but I get the error TypeError: angular.element(...).getAttribute is not a function

我有以下控制器...我正在尝试从 HTML 输入中获取namerating属性,但出现错误TypeError: angular.element(...).getAttribute is not a function

app.controller('courseReview', function ($scope, $http) {

  $scope.rateThis = function rateThis(el){
    var elName = angular.element(el).getAttribute('name');
    var rating = angular.element(el).getAttribute('rating');
    document.getElementById(elName+'Rating').value = rating;
  }
});

HTML

HTML

<div ng-controller="courseReview">
  <!-- radio input -->
  <input class="star-5" id="wstar-5" rating="5" type="radio" name="welcome" ng-click="rateThis(this)"/>
</div>

Is there another way to do this?

有没有其他方法可以做到这一点?

回答by Nikhil Aggarwal

As per the documentation "https://docs.angularjs.org/api/ng/function/angular.element", to get attribute of an element you need to use

根据文档“ https://docs.angularjs.org/api/ng/function/angular.element”,获取您需要使用的元素的属性

.attr('name');

in place of

代替

.getAttribute('name');

Important

重要的

You are passing thisin your html, here thiswill not pass the DOM element to the function, rather it will refer to the scope. To pass the current element pass $event

您传入的this是 html,这里this不会将 DOM 元素传递给函数,而是引用作用域。传递当前元素pass$event

HTML Change

HTML 更改

ng-click="rateThis(this)"to ng-click="rateThis($event)"

ng-click="rateThis(this)"ng-click="rateThis($event)"

JS Change

JS变化

$scope.rateThis = function rateThis($event){
    var elName = angular.element($event.target).attr('name');
    var rating = angular.element($event.target).attr('rating');
    document.getElementById(elName+'Rating').value = rating;
}

For reference - http://plnkr.co/edit/ZQlEG33VvE72dOvqwnpy?p=preview

供参考 - http://plnkr.co/edit/ZQlEG33VvE72dOvqwnpy?p=preview