javascript - AngularJS 1.XX - 为什么有人会对指令使用 "M"限制?

标签 javascript angularjs

我知道 Angular Directive(指令)可以用四种方式定义:

'A' - only matches attribute name
'E' - only matches element name
'C' - only matches class name
'M' - only matches comment

例如带有限制“M”的指令:

angular.module('exampleApp', [])
   .directive('myDirective', function() {
      return {
         restrict: 'M',
         ...
      };
});

并在 HTML 中声明指令

<!-- directive: my-directive -->

但是为什么有人会对指令使用 M 限制?我觉得这真的很奇怪。因为如果我注释掉代码,我不希望它运行。那为什么会这样呢?

最佳答案

来自docs :

Best Practice: Prefer using directives via tag name and attributes over comment and class names. Doing so generally makes it easier to determine what directives a given element matches.

Best Practice: Comment directives were commonly used in places where the DOM API limits the ability to create directives that spanned multiple elements (e.g. inside elements). AngularJS 1.2 introduces ng-repeat-start and ng-repeat-end as a better solution to this problem. Developers are encouraged to use this over custom comment directives when possible.

现在使用它不是好的做法。

根据这个post它通常仅用于向后兼容和传递标记验证。

下面是如何使用它的例子

(function() {
  angular
    .module('exampleApp', [])
    .directive("comment", function() {
      return {
        restrict: 'M',
        replace : true,
        template : "<h1>Made by a comment directive!</h1>",
        link: function(scope, element, attrs) {
          console.log(attrs.comment);
        }
      };
    })
})();
<!DOCTYPE html>
<html ng-app='exampleApp'>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body>

</body>

<body>
  <!-- directive: comment comment argument string -->
</body>

</html>

关于javascript - AngularJS 1.XX - 为什么有人会对指令使用 "M"限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39590290/

相关文章:

javascript - 单击按钮以使用 jquery 删除所有刻度线?

javascript - 在 Ionic/Angular JS 中删除基于侧菜单的模板中的导航栏

javascript - 创建鼠标选择框

javascript - 使用 Jquery 将带有 Class 的 Span 添加到输入标记

javascript - $$hashKey 匹配和选择菜单的选定值

html - 如何获取 Angular 的grails数组

javascript - 无法使用 Angular.js 从表中删除预期的行

angularjs - NPM 开始抛出错误

javascript - Google Apps 脚本中的 ng-Change 等价物

javascript - 在 sessionStorage 中保存 Javascript 对象