指令这节是最难也是最重要的一节,接下来我们来学习一下指令和指令之间是如何通信的。
一、我们要实现的效果如下:
二、源码示例
/*
* accordion可折叠扩展菜单示例
* 涉及指令嵌套,指令与指令之间的通信
*/
myDirec.controller("SomeController2",function($scope) {
$scope.expanders = [{
title : 'Click me to expand',
text : 'Hi there folks, I am the content that was hidden but is now shown.'
}, {
title : 'Click this',
text : 'I am even better text than you have seen previously'
}, {
title : 'Test',
text : 'This is a test,hh~'
}];
});
//定义accordion指令用于协调控制器
myDirec.directive('accordion', function() {
return {
restrict : 'EA',
replace : true,
transclude : true,
template : '<div ng-transclude></div>',
controller : function() {
var expanders = [];
//用于关闭其他的expander
this.gotOpened = function(selectedExpander) {
angular.forEach(expanders, function(expander) {
if (selectedExpander != expander) {
expander.showMe = false;
}
});
};
//用于注册expander
this.addExpander = function(expander) {
expanders.push(expander);
};
}
};
});
//定义expander指令
myDirec.directive('expander2', function() {
return {
restrict : 'EA',//只能放在元素或者属性上
replace : true, //格式可以替换
transclude : true, //能够让你移动一个标识符的原始子节点到一个新模板的位置
require : '^?accordion',//从在相同元素上的标识符获取控制器,该控制器是可选
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);
};
}
};
});<div ng-controller='SomeController2'>
<accordion>
<expander2 class='expander'ng-repeat="expander in expanders" expander-title='expander.title'>
{{expander.text}}
</expander2>
</accordion>
</div>三、分析流程
原文:http://blog.csdn.net/u010834071/article/details/45100209