AngularJs學習筆記__4、自定義指令

AngularJs可以自定義指令。指令一般有4中聲明方式:

E - 元素名稱: <my-directive></my-directive>
A - 屬性: <div my-directive="exp"> </div>
C - 類名: <div class="my-directive: exp;"></div>
M - 註釋: <!-- directive: my-directive exp -->

下面直接看實例:

新建一個index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="zh"  ng-app="expanderModule">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AngularJs自定義指令</title>
<script type="text/javascript" src="js/angular.js"></script>
<script type="text/javascript" src="js/index.js"></script>
  <link rel="stylesheet" type="text/css" href="css/ExpanderSimple.css"/>
</head>
<body>
	<div ng-controller="SomeController">
		<expander class="expander" expander-title="title">
			{{text}}
		</expander>
	</div>
</body>
</html>
新建一個css文件ExpanderSimple.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;
}
在新建一個index.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(){
                scope.showMe = !scope.showMe;
            };
        }
    };
});
expanderModule.controller('SomeController',function($scope) {
    $scope.title = '點擊展開';
    $scope.text = '這是內部的內容';
});
運行看一下效果,這裏我沒有用測試框架,而是直接部署在tomcat運行:

效果如下:


說明:directive用來定義指令;原來的expander標籤被替換了,這是因爲設置了屬性replace:true;ng-transclude指令會保留原來標籤中的內容,但是同時要設置屬性transclude:true;restrict : 'EA',,用來指明標籤的聲明方式,EA,指明指令聲明方式爲元素和屬性。



發佈了71 篇原創文章 · 獲贊 12 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章