让前端飞前端是万能的

AngularJS 自定义指令

2018-08-14  本文已影响2人  肆意木

AngularJS 指令除了基本了的 app、init、model、repeat我们还可以调用自己定义的指令,调用方式有四种:

E :元素名
A:属性
C:类名
M:注释

  1. 元素名
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="app">

<test></test>
<script>
    var app = angular.module("app", []);
    app.directive("test", function () {
        return {
            restrict: "E",   //可省略,默认是EA,即元素名和属性
            template: "这是自定义的通过元素名调用"
        }
    })
</script>
</body>
</html>
//这是自定义的通过元素名调用
  1. 属性
<body ng-app="app">

<div test></div>
<script>
    var app = angular.module("app", []);
    app.directive("test", function () {
        return {
            restrict: "A",   //可省略,默认是EA,即元素名和属性
            template: "这是自定义的通过属性调用"
        }
    })
</script>
</body>

//这是自定义的通过属性调用
  1. 类名
<body ng-app="app">

<div class=" test"></div>
<script>
    var app = angular.module("app", []);
    app.directive("test", function () {
        return {
            restrict: "C", 
            template: "这是自定义的通过类名调用"
        }
    })
</script>
</body>
//这是自定义的通过类名调用
  1. 注释
<body ng-app="app">

 <!-- directive: test -->

 <script>
    var app = angular.module("app", []);
    app.directive("test", function () {
        return {
            restrict: "M",
            replace : true,
            template: "<h1>这是自定义的通过注释调用</h1>"
        }
    })
</script>

</body>
//这是自定义的通过注释调用

PS:一定要在 test 左右留空格;

上一篇下一篇

猜你喜欢

热点阅读