2.4.2 AngularJS自定义指令 accordding expander实现 - OhNaNaSun/angularBlog GitHub Wiki
<div ng-app="myApp">
<div ng-controller="helloCtrl">
<expander expand-title="title">
{{text}}
</expander>
</div>
</div>
var myApp = angular.module("myApp", []);
myApp
.controller("helloCtrl", function($scope) {
$scope.title="点击展示";
$scope.text = "hello everybody~";
})
.directive("expander", function() {
return {
restrict: "AEC",
replace: true,
transclude:true,
scope: {"expandTitle": "="},
template: "<div><span ng-click='toggle()'>{{expandTitle}}"+"</span><br/>"+
"<span ng-show='showMe' ng-transclude></span></div>",
link: function(scope, elem, attr){
scope.showMe = false;
scope.toggle = function(){
scope.showMe = !scope.showMe;
console.log(scope.showMe);
}
}
}
})
一个指令一个作用域。according父级作用域保存的各expander的scope
<div ng-app="myApp">
<div ng-controller="helloCtrl">
<according>
<expander ng-repeat="expanditem in expanderArr" expand-title="expanditem.title">
{{expanditem.text}}
</expander>
</according>
</div>
</div>
var myApp = angular.module("myApp", []);
myApp
.controller("helloCtrl", function($scope) {
$scope.expanderArr = [
{
"title": "点击展示一",
"text": "hello everybody~"
},
{
"title": "点击展示二",
"text": "hello everybody~~"
},
]
})
.directive("according", function(){
return {
restrict:"AEC",
transclude: true,
template: "<div ng-transclude></div>",
controller: function(){
var expandArr = [];
this.getAllClose = function(expand){
expandArr.forEach(function(item){
if(item !== expand){
item.showMe = false;
}
})
};
this.addExpander = function(expan){
expandArr.push(expan);
};
}
}
})
.directive("expander", function() {
return {
restrict: "AEC",
replace: true,
transclude:true,
require:"^according",
scope: {"expandTitle": "="},
template: "<div><span ng-click='toggle()'>{{expandTitle}}"+"</span><br/>"+
"<span ng-show='showMe' ng-transclude></span></div>",
link: function(scope, elem, attr, superCtrl){
superCtrl.addExpander(scope);
scope.showMe = false;
scope.toggle = function(){
superCtrl.getAllClose(scope);
scope.showMe = !scope.showMe;
console.log(scope.showMe);
}
}
}
})