How are the attribute prefixes "x-" and "data-" used in AngularJS

14,779

Solution 1

The HTML5 spec allows for arbitrary attributes as long as they're prefixed with data- like so:

<div data-myattribute=""></div>

Whereas this would be invalid HTML5:

<div myattrbute=""></div>

For more information on data- attributes, have a look here.

As for "x-" attributes, I think you mean "x:" attributes and elements, which are specific to XHTML validation...

To expand on this, if you were to (for some reason) be using XHTML, you can define custom attributes with namespacing like so (and I'm just summarizing the gist here):

<html xmlns:x="http://sample.com/mynamespace">
<body>
   <div x:whatever=""></div>
   <x:mytag></x:mytag>
</body>
</html>

where the URL in xmlns is really just to prevent conflicts between like elements. Also, a DTD for the custom elements and attributes could be provided for validation purposes as a part of your DOCTYPE declaration.

*behavior in browsers is going to vary with this xmlns approach.

In summary, though: With most browsers released in the last three years, or IE8+ you're not going to have to worry about any of these things. Only in very specific situations will you really care.

Solution 2

From the HTML5 spec: http://www.w3.org/html/wg/drafts/html/master/single-page.html

Attribute names beginning with the two characters "x-" are reserved for user agent use and are guaranteed to never be formally added to the HTML language.

Also:

For markup-level features that are intended for use with the HTML syntax, extensions should be limited to new attributes of the form "x-vendor-feature", where vendor is a short string that identifies the vendor responsible for the extension, and feature is the name of the feature. New element names should not be created. Using attributes for such extensions exclusively allows extensions from multiple vendors to co-exist on the same element, which would not be possible with elements. Using the "x-vendor-feature" form allows extensions to be made without risk of conflicting with future additions to the specification.

Share:
14,779
sthomps
Author by

sthomps

Software Engineer @ Gilt Groupe

Updated on June 04, 2022

Comments

  • sthomps
    sthomps about 2 years

    I'm new to Angular and trying to understand what the "x-" and "data-" prefixes mean. In the directives documentation (http://docs.angularjs.org/guide/directive) it says that these prefixes will make the directive "HTML validator compliant". What exactly does this mean?