angularjs 自定义指令(directive)

自定义指令(directive)

使用 .directive 函数来添加自定义的指令。

要调用自定义指令,HTML 元素上需要添加自定义指令名。

例子:使用驼峰法来命名一个指令, demoDirective, 但在使用它时需要以 - 分割, demo-directive:

<!DOCTYPE html>
<html>
<head>
  <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'/>
  <title>自定义指令(directive)的简单demo</title>
</head>
<body ng-app="myApp">
  <h3>自定义指令(directive)</h3>
  <hr>
  <h4>自定义指令的四种调用方式:</h4>
	元素名调用: <demo-directive></demo-directive>
  属性调用:<div demo-directive></div>
  <pre>
    元素名与属性控制的js代码:
    var app = angular.module("myApp", []);
    app.directive("demoDirective", function() {
        return {
            template : "<h1>自定义指令!</h1>"
        };
    });
  </pre>
  类名调用:<div class="demo-directive"></div>
  <pre>
    类名控制的js代码:
    var app = angular.module("myApp", []);
    app.directive("demoDirective", function() {
        return {
            restrict : "C",
            template : "<h1>自定义指令!</h1>"
        };
    });
  </pre>
  注释调用:<!-- directive: demo-directive -->
  <pre>
    注释控制的js代码:
    var app = angular.module("myApp", []);
    app.directive("demoDirective", function() {
        return {
            restrict : "M",
            replace : true,
            template : "<h1>自定义指令!</h1>"
        };
    });
  </pre>
  <script type="text/javascript" src="https://code.angularjs.org/1.7.5/angular.min.js"></script>
  <script type="text/javascript">
    var app = angular.module("myApp", []);
    app.directive("demoDirective", function() {
        return {
            template : "<h1>自定义指令!</h1>"
        };
    });
  </script>
</body>
</html>

自定义指令的限制使用:你可以限制你的指令只能通过特定的方式来调用。

restrict 值可以是以下几种:

E 作为元素名使用
A 作为属性使用
C 作为类名使用
M 作为注释使用
restrict 默认值为 EA, 即可以通过元素名和属性名来调用指令。

原文地址:https://www.cnblogs.com/jing428/p/10132046.html