探討angularJS中指令與指令的通訊
指令這節是最難也是最重要的一節,接下來我們來學習一下指令和指令之間是如何通訊的。
一、我們要實現的效果如下:
二、源碼樣本
控制器部分程式碼範例
/* * 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 : ' ', 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 : '' + '{{title}}' + ' ' + '', link : function(scope, element, attrs, accordionController) { scope.showMe = false; accordionController.addExpander(scope); scope.toggle = function toggle() { scope.showMe = !scope.showMe; accordionController.gotOpened(scope); }; } }; }); 頁面程式碼範例
{{expander.text}}
三、分析流程
頁面載入時將expander註冊完畢然後通過ng-repeat遍曆輸出,此時的showMe屬性為false; 當我們點擊其中一個時觸發了toggle事件,此時showMe屬性更改為true,表示開啟,這個時候text的內容就可以顯示了。當然這裡面用到了ng-show命令,不知道的可以查閱一下該屬性的用法。 然後調用gotOpend方法依次將其他未被選擇的expander進行依次關閉。