In the ANGULARJS development Some experience summary essay mentioned we need to according to business but angular controller, avoid too big omnipotent God controller, we separated controller, But sometimes we need to communicate in the controller, generally for a relatively simple communication mechanism, tell the companion controller one of my things you care about changed, how to do? If you are a JavaScript programmer you will naturally think of asynchronous callback responsive communication-event mechanism (or message mechanism). Yes, that's the only way Angularjs solves the mechanism of communication between controllers, in short, this is angular.
ANGULARJS provides a bubbling and tunneling mechanism for us in scope, $BROADCAST broadcasts events to all child controllers, while $emit passes event bubbling to the parent controller,$ On is a Angularjs event registration function, and with this we can quickly angularjs to resolve the communication between the ANGULARJS controller, the code is as follows: View:
1 <div ng-app= "app" ng-controller= "parentctr" >2 <div ng-controller= "childCtr1" >name:3 < Input ng-model= "name" type= "text" ng-change= "Change (name);"/>4 </div>5 <div ng-controller= " ChildCtr2 ">ctr1 name:6 <input ng-model=" Ctr1name "/>7 </div>8 </div>
Controller:
1 Angular.module ("app", []). Controller ("parentctr", 2 function ($scope) {3 $scope. $on ("Ctr1namechange", 4 5 function (event, msg) {6 console.log ("parent", msg), 7 $scope. $broadcast ("Ctr1namechangefromparrent", msg); 8 }); 9}). Controller ("ChildCtr1", function ($scope) {ten $scope. Change = function (name) { Console.log ("ChildCtr1") , name), $scope. $emit ("Ctr1namechange", name), };14}). Controller ("CHILDCTR2", function ($scope) {15 $scope. $on ("Ctr1namechangefromparrent", function (event, msg) { Console.log (" ChildCtr2 ", msg); $scope. ctr1name = msg;20 }); 21});
The name change here is CHILDCTR1 to the parent controller, and the parent controller wraps the event to broadcast to all the child controllers, while CHILDCTR2 registers the change event and changes itself. Note that the parent controller must change the event name when broadcasting.
Jsfiddle Link: http://jsfiddle.net/whitewolf/5JBA7/15/
Broken Wolf
Source: http://www.cnblogs.com/whitewolf/
"Turn" ANGULARJS communication mechanism between controllers