The use of ANGULARJS, found controller between the value of transmission, more troublesome, after several articles will be said a number of ways.
One, Angularjs $broadcast $emit $on Management thought
In a controller, a method is triggered by an event, in which a variable is defined by $broadcast or $emit in the method, which is obtained through $on within the parent, the child controller.
Examples illustrate the usage of Angularjs $broadcast $emit $on
1,html Code
The code is as follows |
|
<div ng-controller= "Parentctrl" > www.111cn.net//Parent <div ng-controller= "Selfctrl" >//Self <a ng-click= "click ()" >click me</a> <div ng-controller= "Childctrl" ></div>//Child </div> <div ng-controller= "Broctrl" ></div>//Peer </div> |
2,js Code
The code is as follows |
|
Phonecatcontrollers.controller (' Selfctrl ', function ($scope) { $scope. Click = function () { $scope. $broadcast (' to-child ', ' child '); $scope. $emit (' to-parent ', ' parent '); } }); Phonecatcontrollers.controller (' Parentctrl ', function ($scope) { $scope. $on (' To-parent ', function (d,data) { console.log (data); //parent can get the value }); $scope. $on (' To-child ', function (d,data) { Console.log (data); //Child not get value }); }); Phonecatcontrollers.controller (' Childctrl ', function ($scope) { $scope. $on (' To-child ', function (d,data) { console.log (data); //child can get the value }); $scope. $on (' To-parent ', function (d,data) { Console.log (data); //parent is not getting the value }); }); Phonecatcontrollers.controller (' Broctrl ', function ($scope) { $scope. $on (' To-parent ', function (d,data) { Console.log (data); The peer cannot get a value }); $scope. $on (' To-child ', function (d,data) { Console.log (data); The peer cannot get a value }); }); |
3, click the output of the Click me
1.child
2.parent
Child
Parent uses the value of $broadcast, only the child to get the value, $emit assigned value, can only be parent, and the level of nothing can be obtained.