How to read angular.element attribute without knowing if it was prefixed with data or x-data

I was wondering if there is a standard way to get an attribute from an angular element without knowing if the attribute name was a data or x-data prefix.

I saw this code inside a directive:

el.attr('x-data-' + attr) || el.attr('data-' + attr) || el.attr(attr).

      

Is this the correct approach, or is there something more standard?

+3


source to share


2 answers


In HTML, you can add an attribute to an element, for example data - *. (Note: Always prefix your attribute with data -)

<div data-tasktype = "somevalue"> </div>

      

In Js file you can get attribute value like

 var val = element.data('tasktype');

      



(note: the prefix part will be skipped here.) Browser: IE9 and up, chrome, etc.

If you are unsure about the browser, or don't know what the naming convention you are going to use for your attribute, you can go for

 el.attr('x-data-' + attr) || el.attr('data-' + attr) || el.attr(attr)

      

+1


source


If this is your own application that will use your directive, and if you know your browser versions well (i.e. not = <= IE8), then I won't bother with prefixes data-

.



On the other hand, if you are developing a directive library for other users and you have no control over browsers or HTML authors, you should just use what you have.

+1


source







All Articles