AngularJS 中属性规范化的基本原理

Rationale behind attribute normalisation in AngularJS

我正在尝试向 w3schools. For creating custom directives the below example has been provided at Custom Directives

学习 AngularJS

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<body ng-app="myApp">

<w3-test-directive></w3-test-directive>

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
    return {
        template : "<h1>Made by a directive!</h1>"
    };
});
</script>

</body>

此处指令的名称在创建时 (w3TestDirective) 与在 HTML (w3-test-directive) 中使用的名称不同。 如果我使用 HTML 元素作为 <w3TestDirective> 我在输出中看不到任何内容。

我看到 AngularJS 需要执行属性规范化。但是,我不明白为什么 AngularJS 需要执行规范化。 有人可以帮助我理解 AngularJS 背后的基本原理吗?

您需要添加 restrict: 'E',以便将指令用作 html 元素。看到这个:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<body ng-app="myApp">

<w3-test-directive></w3-test-directive>

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
    return {
     restrict: 'E',
     template : "<h1>Made by a directive!</h1>"
    };
});
</script>

</body>

关于 AngularJS

中的属性规范化

We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel). However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model). See AngularJS Developer Guide - Directive Normalization. – georgeawg

感谢georgeawg,我无法更好地解释它。


在使用 AngularJS 1.x 时,您必须配置 restrict,在您的情况下 E 用于 elementrestict: 'E' 与您的元素标签匹配 <w3-test-directive></w3-test-directive>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<body ng-app="myApp">

<w3-test-directive></w3-test-directive>

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
    return {
        restrict: 'E',
        template : "<h1>Made by a directive!</h1>"
    };
});
</script>

</body>


虽然使用 AngularJS 1.5+ restrict 默认设置为 EA,这将与 elementattribute 匹配。 restrict: 'EA' 匹配 <w3-test-directive></w3-test-directive><span w3-test-directive=""></span> 在这种情况下,您的代码可以正常工作:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp">

<w3-test-directive></w3-test-directive>
<span w3-test-directive=""></span>

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
    return {
        template : "<h1>Made by a directive!</h1>"
    };
});
</script>

</body>