user3693057
user3693057

Reputation:

Get data-attribute value with angular

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

Upvotes: 0

Views: 6850

Answers (2)

Surjit Sidhu
Surjit Sidhu

Reputation: 387

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' ) );

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

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');

Upvotes: 2

Related Questions