用angularJS实现Bootstrap的“手风琴”
主页面代码(发现Bootstrap官网上手风琴的实例样式有问题,在这里依然使用3.0.~版本)
<!DOCTYPE html> <html ng-app="ct"> <head lang="en"> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="bootstrap-3.3.4-dist/css/bootstrap.css"/> <link rel="stylesheet" href="bootstrap-3.3.4-dist/css/bootstrap-r.css"/> </head> <body> <hr> <div class="container" ng-controller="c1"> <kittencup-group> <kittencup-collapse ng-repeat="collapse in Data" head="collapse.a"> <span ng-bind="collapse.b"></span> </kittencup-collapse> </kittencup-group> </div> </body> <script src="../angular.js"></script> <script> var app = angular.module("ct",[]); app.factory("Data",function(){ return [ { a:"错你妹啊", b:"contents1" }, { a:"title2", b:"contents2" } ] }); app.controller("c1",['$scope','Data', function($scope,Data){ //由ctrl拿到数据加载给view $scope.Data = Data; }]); app.directive('kittencupGroup', function(){ return { restrict:"EA", transclude:true, replace:true, template:"<div class='panel-group' ng-transclude></div>", controller:function(){ this.collapseGroup = []; this.otherClose = function(currCollaps){ angular.forEach(this.collapseGroup, function(collaps){ if(collaps !== currCollaps){ collaps.isOpen = true; } }); } } } }); app.directive('kittencupCollapse', function(){ return { restrict:"EA", require:"^kittencupGroup", replace:true, templateUrl:"templates/contents.html", transclude:true, scope:{ head:"=" }, link: function(scope, elements, attrs, superCtrl){ scope.isOpen = true; scope.open = function(){ scope.isOpen = !scope.isOpen; superCtrl.otherClose(scope); }; superCtrl.collapseGroup.push(scope); } } }); </script> </html>
模板代码:
<div class="panel panel-default"> <div class="panel-heading" ng-click="open()"> <h4 class="panel-title"> <a href="#collapseOne"> <span ng-bind="head"></span> </a> </h4> </div> <div class="panel-collapse" ng-class="{collapse: isOpen}"> <div class="panel-body" ng-transclude> </div> </div> </div>