angularjs $broadcast $emit $on 事件觸發controller間的值傳遞

來源:互聯網
上載者:User

標籤:

使用angularjs,發現controller間的值傳遞,比較麻煩的,以後幾篇文章會陸續說幾種方法。

一,angularjs $broadcast $emit $on的處理思想

在一個controller裡面通過事件觸發一個方法,在方法裡面通過$broadcast或$emit來定義一個變數,在父,子controller裡面通過$on來擷取。

 

二,執行個體說明angularjs $broadcast $emit $on的用法

1,html代碼

查看複製列印?
  1. <div ng-controller="ParentCtrl">                  //父級  
  2.     <div ng-controller="SelfCtrl">                //自己  
  3.         <a ng-click="click()">click me</a>  
  4.         <div ng-controller="ChildCtrl"></div>     //子級  
  5.     </div>  
  6.     <div ng-controller="BroCtrl"></div>           //平級  
  7. </div>  

2,js代碼

查看複製列印?
  1. phonecatControllers.controller(‘SelfCtrl‘, function($scope) {  
  2.     $scope.click = function () {  
  3.         $scope.$broadcast(‘to-child‘, ‘child‘);  
  4.         $scope.$emit(‘to-parent‘, ‘parent‘);  
  5.     }  
  6. });  
  7.   
  8. phonecatControllers.controller(‘ParentCtrl‘, function($scope) {  
  9.     $scope.$on(‘to-parent‘, function(d,data) {  
  10.         console.log(data);         //父級能得到值  
  11.     });  
  12.     $scope.$on(‘to-child‘, function(d,data) {  
  13.         console.log(data);         //子級得不到值  
  14.     });  
  15. });  
  16.   
  17. phonecatControllers.controller(‘ChildCtrl‘, function($scope){  
  18.     $scope.$on(‘to-child‘, function(d,data) {  
  19.         console.log(data);         //子級能得到值  
  20.     });  
  21.     $scope.$on(‘to-parent‘, function(d,data) {  
  22.         console.log(data);         //父級得不到值  
  23.     });  
  24. });  
  25.   
  26. phonecatControllers.controller(‘BroCtrl‘, function($scope){  
  27.     $scope.$on(‘to-parent‘, function(d,data) {  
  28.         console.log(data);        //平級得不到值  
  29.     });  
  30.     $scope.$on(‘to-child‘, function(d,data) {  
  31.         console.log(data);        //平級得不到值  
  32.     });  
  33. });  

3,點擊Click me的輸出結果

  1. child  
  2. parent  

用$broadcast賦的值,只能子級得到值;$emit賦的值,只能父級得到;而平級的什麼都不能得到。

angularjs $broadcast $emit $on 事件觸發controller間的值傳遞

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.