Why can't I use data- * as a directive attribute name in AngularJS?

On t of its plunger, you may notice strange behavior with the data-* attribute name template in the directive.

Call:

 <body ng-app="apptest" ng-controller="Controller"> Test of data named attribute : <br/> <directivetest data-test="vartest" test="vartest" another-test="vartest"></directivetest> </body> 

directives:

 angular.module('apptest', []) .controller('Controller', ['$scope', function($scope) { $scope.vartest = "This is a test"; } ]) .directive('directivetest', function() { return { restrict: 'E', scope: { dataTest: '=', test: '=', anotherTest: '=' }, templateUrl: "directive.html" } }); 

will take into account all directivetest attributes, but data-test and therefore will display:

 Test of data named attribute : Attribute with data-* name : Attribute with regular name : This is a test Attribute with an other regular name : This is a test 

I wonder why this is happening (I spent 4 hours before I realized that this is a problem).

It seems impossible to name the data-* directive, why is this?

I read something about it here http://www.w3schools.com/tags/att_global_data.asp , why is my attribute undefined? Is it just not readable by the browser?

+7
javascript angularjs html5
source share
3 answers

The prefix forms of data- directive name names allow HTML validators to work because user-data attributes in HTML5 follow this form. AngularJS directive names are normalized to support user data attributes:

The normalization process is as follows:

  • Strip x- and data- on the front of the element / attributes.
  • Convert the name : - or _ -delimited name to camelCase.
+13
source share

Angular automatically normalizes attributes. Things like data-test="..." , x-test="..." and test="..." are considered the same. You must choose one of the ways to write custom attributes and stick to it; not mixing and matching.

+2
source share

This is because Angular strip x- and data are on the front of the element / attributes. So in your case you have two attributes called test and one overwrites the other. As an example, I used forkled your plunker: Plunker

 <directivetest data-foo="vartest" test="vartest" another-test="vartest"></directivetest> scope: { foo: '=', test: '=', anotherTest: '=' } 
0
source share

All Articles