探討angularJS中指令與指令的通訊

來源:互聯網
上載者:User

探討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進行依次關閉。

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.