@dreamapplehappy
2014-12-18T17:37:41.000000Z
字数 2139
阅读 2931
angularjs
组件
先看代码吧:
/*---ng-app表示angularjs程序的开始---*/
<html lang="en" ng-app="myModule">
<head>
<meta charset="UTF-8">
<title>Expander</title>
/*---引入外部的bootstrap文件和expander.css文件---*/
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
<link rel="stylesheet" href="expander.css">
/*---引入angularjs文件和外部的expander.js文件---*/
<script src="angular.min.js"></script>
<script src="expander.js"></script>
</head>
/*---控制器myController控制整个body---*/
<body ng-controller="myController">
<div class="container">
<expander-container>
<expander ng-repeat="expander in expanders" expander-title="expander.title">{{expander.text}}</expander>
</expander-container>
</div>
</body>
</html>
先看代码吧
/*声明自己的模块myModule*/
var myModule = angular.module('myModule', []);
myModule.controller('myController', ['$scope', function($scope){
$scope.expanders = [
{title: 'Hello World', text: '是不是除了Hello World,你什么也不会写?'},
{title: 'Emberjs', text: 'AngularJS很厉害吗?我不觉得。-Emberjs'},
{title: 'AngularJS', text: '楼上说话要注意一点!'}
];
}]);
myModule.directive('expanderContainer', function(){
return {
restrict: 'AE',
template: '<div ng-transclude></div>',
replace: true,
transclude: true,
controller: function(){
/*声明一个数组,用来存放下面expander指令生成的内容*/
var expanders = [];
/*添加expander指令生成的内容*/
this.addExpander = function(expander){
expanders.push(expander);
}
/*对选择中的expander进行一些操作*/
this.getOpend = function(selectedExpander){
angular.forEach(expanders, function(expander){
if(selectedExpander != expander){
expander.show = false;
}
});
}
}
};
});
myModule.directive('expander', function(){
return {
/*作用域的绑定*/
scope: {title: '=expanderTitle'},
/*声明依赖*/
require: '^?expanderContainer',
restrict: 'AE',
template: '<div>'+
'<div class="title" ng-click="toggle()">{{title}}</div>'+
'<div class="text" ng-show="show" ng-transclude></div>'+
'</div>',
replace: true,
transclude: true,
/*在连接阶段进行操作*/
link: function(scope, iElm, iAttrs, controller) {
scope.show = false;
controller.addExpander(scope);
scope.toggle = function toggle(){
scope.show = !scope.show;
controller.getOpend(scope);
}
}
};
});