最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - getAttribute value with AngularJS - Stack Overflow

programmeradmin7浏览0评论

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

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

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

Is there another way to do this?

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

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

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

Is there another way to do this?

Share Improve this question edited Jul 7, 2018 at 18:43 Rui Lopes 1061 silver badge12 bronze badges asked Jul 10, 2015 at 7:24 StudioTimeStudioTime 24k40 gold badges128 silver badges215 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 16

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

.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

HTML Change

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

JS Change

$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

发布评论

评论列表(0)

  1. 暂无评论