Angularjs[25] - 自定义指令(1)(restrict, template, replace 属性)

自定义指令:

  1. module.directive(name,directiveFactory)
  2. @see $compileProvider.directive()

⚠️  不要使用 ng 为指令,若指令名为 xxx-yyy,在设置指令名时应为 xxxYyy 即驼峰命名法。

  • restrict: 可以任意组合四种风格,如果忽略 restrict,默认为A。
字母 风格 示例
E 元素 <my-dir></my-dir>
C 样式类 <span class="my-dir:exp;"></span>
A 属性 <span my-dir="exp"></span>
M 注释 <!-- directive: my-dir:exp-->

 

  • template: 模板内容,这个内容根据 replace 参数设置替换节点或仅替换节点内容。
  • replace: 若此配置为 true 则替换指令所在元素,若为 false 或不指定,则把当前指令追加到所在元素内。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div ng-app="myApp">
        <custom-tags>222</custom-tags>
        <div class="custom-tags"></div>
        <div custom-tags></div>
        <!-- directive: custom-tags -->
    </div>

<script type="text/javascript" src="../../vendor/angular/angularjs.js"></script>
<script type="text/javascript" src="app/index.js"></script>
</body>
</html>
var myApp = angular.module('myApp',[],['$compileProvider',function ($compileProvider) {
    $compileProvider.directive('customTags',function () {
        return{
            restrict: 'ECAM',
            template:'<div>custom-tags-html</div>',
            replace: true
        }
    });
}])

 

posted @ 2017-01-31 18:46  。娴  阅读(769)  评论(0编辑  收藏  举报