0

I'm trying to get the value of a data-attributes element in angular. I have my controller like this:

controller code:

(function() {

  'use strict';

  var app = angular.module('myApp');

  app.controller('globalCtrl', function ($scope) {

      var dataPreview = document.getElementsByClassName('element');


      $scope.item = {
        name: dataPreview.getAttribute("data-branch"),
        shortname: dataPreview.getAttribute("data-short-name")

      };

  });

}(window, window.angular));

But the console returns the following error:

dataPreview.getAttribute is not a function

I'm lost trying to find a solution to this error, can someone tell me what's wrong with my code

2 Answers 2

2

You need to iterate over the elements when you use class selector.

For eg:

var dataPreview = document.getElementsByClassName('element')[0];
// here 0 index element will be selected and then only you'll be able to use 
//  getAttribute method

If you use id, then you don't need to iterate:

var dataPreview = document.getElementById('element');
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your help! I had forgotten that point ;)
0

simple html tag with data attribute

<div class="branchUI" data-branch="some branch">I'm ok here</div>

I added class to button to get by querySelector, then get data attribute same as below

var branchUI = angular.element( document.querySelector( '.branchUI' ) );
console.log( branchUI.data( 'branch' ) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.