The controller communication mechanism of ANGULARJS is described in this paper. Share to everyone for your reference, specific as follows:
Some experience in ANGULARJS development mentioned that we need to differentiate angular controller according to business, avoid the Almighty God controller, we separated controller, But sometimes we need to communicate in the controller, generally for relatively simple communication mechanism, tell the companion controller one of my care things changed, how to do? If you are a JavaScript programmer you will naturally think of asynchronous callback response-event mechanism (or message mechanism). Yes, that's the only way that ANGULARJS solves the controller communication mechanism, in short this is angular way.
ANGULARJS provides a bubbling and tunneling mechanism for us in scope, $BROADCAST broadcasts events to all child controller, while $emit passes events bubbling to the parent controller,$ On is the Angularjs event registration function, with which we can quickly resolve the communication between the ANGULARJS controller in a ANGULARJS way, the code is as follows:
View:
<div ng-app= "App" ng-controller= "parentctr" >
<div ng-controller= "childCtr1" >name:
<input Ng-model= "Name" type= "text" ng-change= "Change (name);"/>
</div>
<div ng-controller= "CHILDCTR2" >CTR1 Name:
<input ng-model= "Ctr1name"/>
</div>
</div>
Controller:
Angular.module ("App", []). Controller ("parentctr",
function ($scope) {
$scope. $on ("Ctr1namechange",
function (event, msg) {
console.log ("parent", msg);
$scope. $broadcast ("Ctr1namechangefromparrent", msg);
})
. Controller ("ChildCtr1", function ($scope) {
$scope. Change = function (name) {
Console.log ("ChildCtr1", name); c10/> $scope. $emit ("Ctr1namechange", name);
Controller ("ChildCtr2", function ($scope) {
$scope. $on ("ctr1namechangefromparrent",
function (event, MSG) {
Console.log ("ChildCtr2", msg);
$scope. ctr1name = msg;});
The name change here is CHILDCTR1 to the parent controller, and the parent controller wraps the event to all the child controller, 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/
I hope this article will help you to Angularjs program design.