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
getAttribute value with AngularJS
提问by Darren Sweeney
I have the following controller... I'm trying to get the name
and rating
attibute from an HTML input, but I get the error TypeError: angular.element(...).getAttribute is not a function
我有以下控制器...我正在尝试从 HTML 输入中获取name
和rating
属性,但出现错误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 this
in your html, here this
will 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