我知道 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/