莫菲    

AngularJs自定义标签多种显示方式

7年前发布  · 1303 次阅读
  AngularJs 

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

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

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

不同方法显示例子:

mytag.php

<!doctype html>
<html lang="ch-zn">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="js/angular.min.js"></script>
    <script src="mytag.js"></script>
</head>
<body>
<div ng-app="mytag">
    <runoob-directive></runoob-directive>
    <!--属性-->
    <div runoob-directive></div>
    <!--类名-->
    <p><strong>注意:</strong> 你必须设置 <b>restrict</b> 的值为 "C" 才能通过类名来调用指令。</p>
    <div class="mytag-directive"></div>
    <p><strong>注意:</strong> 我们需要在该实例添加 <strong>replace</strong> 属性, 否则评论是不可见的。</p>

    <p><strong>注意:</strong> 你必须设置 <b>restrict</b> 的值为 "M" 才能通过注释来调用指令。</p>
    <!-- directive: comment-directive -->
</div>
</body>
</html>
mytag.js

/**
 * Created by user on 2016/5/28.
 */
var tag = angular.module('mytag', []);
tag.directive("runoobDirective", function() {
    return {
        template : "<h1>自定义指令!</h1>"
    };
});
tag.directive("mytagDirective", function() {
    return {
        restrict : "C",
        template : "<h1>自定义指令!</h1>"
    };
});
tag.directive("commentDirective", function() {
    return {
        restrict : "M",
        replace : true,
        template : "<h1>自定义指令!</h1>"
    };
});