为什么我不能用数据 - *作为指令的属性名称,JS角 [英] Why can't I use data-* as a directive's attribute name in angular js

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

问题描述

在以下plunker你可以看到带有属性名称的模式在指令数据 - *一个奇怪的行为。

http://plnkr.co/edit/l3KoY3?p=$p$ PVIEW

召唤:

 <机身NG-应用=apptestNG控制器=控制器>
  数据测试指定属性:
  < BR />
  < directivetest数据测试=vartest测试=vartest另一个测试=vartest>< / directivetest>
< /身体GT;

该指令:

  angular.module('apptest',[])
  .controller('控制',['$范围',
    功能($范围){
      $ scope.vartest =这是一个测试;
    }
  ])
  .directive('directivetest',函数(){
    返回{
      限制:'E',
      范围: {
        数据测试:'=',
        试验:=,
        anotherTest:'='
      },
      templateUrl:directive.html
    }
  });

将采取directivetest所有属性考虑,但数据的测试,因此显示:


 数据测试指定属性:
与数据 - * name属性:
与常规Name属性:这是一个测试
与其他普通的name属性:这是一个测试


我想知道为什么发生这种情况(我浪费了前4小时我想通了,这是问题)。

这似乎是不可能的命名指令数据 - *,这是为什么?

我读了一些有关在这里 http://www.w3schools.com/tags/att_global_data。 ASP ,这是为什么我的属性是未定义?这根本就不是由浏览器读取?


解决方案

数据 - prefixed指令的名称形式允许HTML验证器,因为的自定义数据的HTML 5特性如下的形成。 AngularJS指令名标准化如下,以支持自定义数据属性:


  

归一化处理是如下:


  
  

      
  • 地带x和从元件的正面数据 - /属性

  •   
  • 的转换:, - 或_分隔的名字驼峰

  •   

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

http://plnkr.co/edit/l3KoY3?p=preview

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 HTML 5 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.

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

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