【问题标题】:Why can't I use data-* as a directive's attribute name in AngularJS?为什么我不能在 AngularJS 中使用 data-* 作为指令的属性名称?
【发布时间】:2015-01-12 13:22:40
【问题描述】:

在 this plunker 上,您会注意到指令中属性名称模式 data-* 的奇怪行为。

电话:

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

指令的:

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"
    }
  });

将考虑 directivetest 的所有属性,但 data-test 并因此显示:

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

我想知道为什么会发生这种情况(我浪费了 4 个小时才发现这是问题所在)。

似乎不可能将指令命名为data-*,这是为什么呢?

我在这里http://www.w3schools.com/tags/att_global_data.asp 读到了一些关于它的内容,这就是我的属性未定义的原因吗?浏览器根本不读取?

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

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

    归一化过程如下:

    • 从元素/属性的前面去除x-data-
    • :-_ 分隔的名称转换为驼峰式。

    【讨论】:

    • 感谢未来。花了半天的时间试图弄清楚为什么我看起来非常温和的指令没有加载,然后才发现名称本身就是问题!
    【解决方案2】:

    这是因为 Angular 从元素/属性的前面剥离了 x- 和 data-。因此,在您的情况下,您有两个名为 test 的属性,一个覆盖另一个。我以你的 plunker 为例:Plunker

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

    【讨论】:

      【解决方案3】:

      Angular 会自动规范化属性。像data-test="..."x-test="..."test="..." 这样的东西被认为是相同的。您应该选择一种编写自定义属性的方式并坚持下去;不混搭。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-25
        相关资源
        最近更新 更多