为什么我不能在AngularJS中使用data- *作为指令的属性名称? [英] Why can't I use data-* as a directive's attribute name in AngularJS?

查看:349
本文介绍了为什么我不能在AngularJS中使用data- *作为指令的属性名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在t plunker 上,您可以注意到属性名称模式的奇怪行为
$ b

 < body ng-app =apptestng-controller =Controller> 
测试名为属性的数据:
< br />
< directivetest data-test =vartesttest =vartestanother-test =vartest>< / directivetest>
< / body>

指令的

  angular.module('apptest',[])
.controller('Controller',['$ scope',
function($ scope){
$ scope.vartest =这是一个测试;
}
])
.directive('directivetest',function(){
return {
restrict:' E',
范围:{
dataTest:'=',
test:'=',
anotherTest:'='
},
templateUrl :directive.html
}
});

会将 directivetest 的所有属性变为帐户但数据测试,因此显示:


 名为属性的数据测试:
具有data- *名称的属性:
具有常规名称的属性:这是一个测试
具有其他常规名称的属性:这是一个测试


我想知道为什么会发生这种情况这是问题)。



似乎无法命名指令数据 - * ,为什么这是什么?



我在这里阅读了一些关于它的信息 http://www.w3schools.com/tags/att_global_data.asp ,这是为什么我的属性是不确定的?它只是不被浏览器读取?

解决方案

data - 指令名称的前缀形式允许HTML验证器工作,因为 自定义数据属性 遵循该表单。 AngularJS指令名称如下 标准化 ,以支持自定义数据属性:


标准化过程如下:


  • 从元素/属性的前面开始 x - 数据 -

  • 转换 - _ - 限定名称为camelCase。



On the this plunker you can notice a strange behavior with the attribute name's pattern data-* in a directive.

The 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>

of the directive :

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 all the attributes of directivetest into account but data-test and therefore 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 am wondering why this happens (I wasted 4 hours before I figured out that it was the issue).

It seems to be impossible to name a directive data-*, why is that?

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

解决方案

The data- prefixed forms of directive names allow HTML validators to work because custom data attributes in HTML5 follow that form. AngularJS directive names are normalized as follows to support custom data attributes:

The normalization process is as follows:

  • Strip x- and data- from the front of the element/attributes.
  • Convert the :, -, or _-delimited name to camelCase.

这篇关于为什么我不能在AngularJS中使用data- *作为指令的属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆