AngularJS directive入门例子

这是《AngularJS》这本书里面提供的一个例子:

JS代码:

var expanderModule=angular.module('expanderModule', [])
expanderModule.directive('expander', function() {
    return {
        restrict : 'EA',
        replace : true,
        transclude : true,
        scope : {
            title : '=expanderTitle'
        },
        template : '<div>'
                 + '<div class="title" ng-click="toggle()">{{title}}</div>'
                 + '<div class="body" ng-show="showMe" ng-transclude></div>'
                 + '</div>',
        link : function(scope, element, attrs) {
            scope.showMe = false;
            scope.toggle = function toggle() {
                scope.showMe = !scope.showMe;
            }
        }
    }
});
expanderModule.controller('SomeController',function($scope) {
    $scope.title = '点击展开';
    $scope.text = '这里是内部的内容。';
});

HTML代码:

<html ng-app='expanderModule'>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <script src="../angular-1.0.3/angular.min.js"></script>
        <link rel="stylesheet" type="text/css" href="ExpanderSimple.css"/>
    </head>
    <body>
        <div ng-controller='SomeController'>
            <expander class='expander' expander-title='title'>
                {{text}}
            </expander>
        </div>
    </body>
    <script src="ExpanderSimple.js"></script>
</html>

CSS代码:

.expander {
    border: 1px solid black;
    width: 250px;
}

.expander>.title {
    background-color: black;
    color: white;
    padding: .1em .3em;
    cursor: pointer;
}

.expander>.body {
    padding: .1em .3em;
}

运行效果如下:



 

compile阶段进行标签解析和变换,link阶段进行数据绑定等操作!

在所有module都装载完毕在之后,compile(element)(scope);开始编译和链接整个dom树(其实就是调用dom上出现的指令)。

第一步:传递应用根节点给$compile函数,开始编译,返回link函数。

第二步:传递根作用域给link函数,开始链接(每个指令分为pre link 和 post link两个过程)

link函数的参数:

    1. scope
      这个就是当前control的$scope对象,没啥好说的。
    2. element
      这个是当前dom节点经过“jquery”处理过后的对象。用过jquery的都知道这个概念。当然这边的jquery是angular自己实现的阉割版的jquery。方法少了许多,不过按angular的话说,够用了。
    3. attrs
      这个对象包含,当前的dom节点上的各种属性标签的值。不过要注意的是这边会将xxx-bbb这种形式的改写成xxxBbb的这种驼峰形式。
原文地址:https://www.cnblogs.com/bonelee/p/6202596.html