标签:
1 通过$broadcast或$emit在controller之间进行值传递,不过这些controller必须是子级或者父级关系, 2 $emit只能向父级parent controller传递事件event与数据data,$broadcast只能向子级child controller传递event与data,$on用于接收event与data.
3 <script> 4 var myapp=angular.module(‘myapp‘,[]); 5 myapp.controller(‘SelfCtrl‘, function($scope) { 6 $scope.click = function () { 7 $scope.$emit(‘to-parent‘, ‘parent‘); 8 $scope.$broadcast(‘to-child‘, ‘child‘); 9 } 10 });//在当前控制器内,分别给父级控制器和子级控制器传递事件和数据 11 12 myapp.controller(‘ParentCtrl‘, function($scope) { 13 $scope.$on(‘to-parent‘, function(d,data) { 14 console.log(data); //父级控制器内监听上面控制器中$emit注册的事件和传递的值 15 }); 16 $scope.$on(‘to-child‘, function(d,data) { 17 console.log(data); //父级控制器内监听不到上面控制器中$broadcast注册的事件和传递的值,因为$broadcast注册的事件和传递的值是给子级的控制器的 18 }); 19 }); 20 21 myapp.controller(‘ChildCtrl‘, function($scope){ 22 $scope.$on(‘to-child‘, function(d,data) { 23 console.log(data); //同理 24 }); 25 $scope.$on(‘to-parent‘, function(d,data) { 26 console.log(data); //同理 27 }); 28 }); 29 30 myapp.controller(‘BroCtrl‘, function($scope){ 31 $scope.$on(‘to-parent‘, function(d,data) { 32 console.log(data); //平级得不到值,因为$broadcast或$emit只能给子级或父级controller传递事件和值 33 }); 34 $scope.$on(‘to-child‘, function(d,data) { 35 console.log(data); //同理 36 }); 37 }); 38 39 </script> 40 41 <body ng-app="myapp"> 42 <div ng-controller="ParentCtrl"> //父级控制器 43 <div ng-controller="SelfCtrl"> //当前控制器 44 <a ng-click="click()">click me</a> 45 <div ng-controller="ChildCtrl"></div> //子级控制器 46 </div> 47 48 <div ng-controller="BroCtrl"></div> //平级控制器 49 </div> 50 </body> 51 52 53
原文:http://blog.51yip.com/jsjquery/1602.html
1 用rootscope定义的值,可以在各个controller中使用: 2 3 var myapp=angular.module(‘myapp‘,[]); 4 5 myapp.controller(‘TestCtrl1‘,[‘$scope‘,‘$rootScope‘, 6 function($scope,$rootScope) { 7 $rootScope.name = ‘123‘; 8 } 9 ]); 10 myapp.controller(‘TestCtrl2‘,[‘$scope‘,‘$rootScope‘, 11 function($scope,$rootScope) { 12 $scope.name = $rootScope.name; 13 } 14 ]); 15 16 <div ng-controller="TestCtrl1"> 17 Iset the global variable.<strong>{{$root.name}}</strong> 18 </div> 19 <div ng-controller="TestCtrl2"> 20 1,get global variable .<strong>{{name}}</strong><br> 21 2,get global variable .<strong>{{$root.name}}</strong> 22 </div>
通过$broadcast或$emit在子级和父级controller之间进行值传递
标签:
原文地址:http://www.cnblogs.com/leyi/p/5058393.html