<!DOCTYPE html>
<html lang="en" ng-app="expanderModule">
<head>
<meta charset="UTF-8">
<title>自定义指令 accordion</title>
<link rel="stylesheet" href="CSS/bootstrap.css">
<style>
.accordion{
border:solid 1px #E3E3E3;
width: 200px;
margin-top: 20px;
margin-left: 20px;
}
.expander{
width: 100%;
}
.title{
background-color: #2f96b4;
}
.body{
background-color: #ffffff;
height:100px;
}
</style>
<script src="angular.min.js"></script>
<script>
var expModule = angular.module('expanderModule',[]);
//accordion通过Controller暴露一部分公共的方法
expModule.directive('accordion',function(){
return{
restrict: 'EA',
replace: true,
transclude: true,
template: '<div class="accordion" ng-transclude></div>',
controller:function () {
var expanders = [];
this.gotOpened = function (selectedExpander) {
angular.forEach(expanders,function (expander) {
if(selectedExpander != expander){
expander.showMe = false;
}
})
}
this.addExpander = function (expander) {
expanders.push(expander);
}
}
}
})
expModule.directive('expander',function () {
return{
restrict: 'EA',
replace : true,
transclude: true,
require:'^?accordion', //依赖外部的accodion,在link 中就可以接受第四个参数accordionController
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,accordionController) {
scope.showMe = false;
accordionController.addExpander(scope);
scope.toggle = function toggle() {
scope.showMe = !scope.showMe;
accordionController.gotOpened(scope);
}
}
}
});
expModule.controller('SomeController',function ($scope) {
$scope.expanders = [{
title:'Click me to expand',
text : "hello,I am the content that was hidden but now is shown."
},{
title:"Click this",
text:"I am even better text that you have seen previously"
},{
title:"Test",
text:"test"
}]
})
</script>
</head>
<body ng-controller="SomeController">
<accordion >
<expander class="expander" ng-repeat="expander in expanders" expander-title="expander.title">
{{expander.text}}
</expander>
</accordion>
</body>
</html>
界面如下图所示: