如何在作用域之间通信呢? 1 <style> 2 div{border:1px solid #ff7300;padding:20px;margin:10px;border-radius: 5px;} 3 </style> 4 <div ng-controller="ParentController"><!--父级--> 5 <div ng-click="clkP()">click--给child</div> 6 <div ng-controller="OneSelfController"><!--自己--> 7 <span ng-click="clkme()">click me</span> 8 <div ng-controller="ChildController"> 9 它是OneSelfController的子级 10 </div><!--子级--> 11 </div> 12 <div ng-controller="siblingsController"> 13 它与OneSelfController是平级 14 </div><!--平级--> 15 </div> 16 17 <script> 18 var app=angular.module('firstApp',[]);//app模块名 19 app.controller('OneSelfController',function($scope){ 20 $scope.clkme=function(){ 21 $scope.$broadcast('sendChild','我给子控制器传递数据'); 22 $scope.$emit('sendParent','冒泡到父元素') 23 } 24 }).controller('ParentController',function($scope){ 25 $scope.$on('sendParent',function(event,data){//监听在子控制器中定义的 sendParent 事件 26 console.log('OneSelfController传过来的',data,event.name,event);//事件名称:sendParent 27 }); 28 $scope.clkP=function(){ 29 $scope.$broadcast('sendAllChild','让siblingsController接收到'); 30 } 31 32 }).controller('ChildController', function($scope){ 33 $scope.$on('sendChild', function(event,data) {//监听在子控制器中定义的 sendChild 事件 34 console.log('ChildCtrl', data,event.name,event);// 事件名称:sendChild 35 }); 36 }).controller('siblingsController', function($scope){ 37 $scope.$on('sendAllChild',function(event,data) { 38 console.log('值过来吧', data); 39 }); 40 //下面事件不会触发 41 $scope.$on('sendParent', function(event,data) { 42 console.log('平级得不到值', data); 43 }); 44 $scope.$on('sendChild', function(event,data) { 45 console.log('平级得不到值', data); 46 }); 47 }); 48 49 </script> 来自:http://www.cnblogs.com/yuzhongwusan/p/4938816.html |
|
来自: 瑶疏影 > 《AngularJS》