In Angularjs Development Experience summary, we mentioned that we need to divide the angular controller according to the business, so as to avoid the overwhelming and omnipotent God controller. We split the controller away, but sometimes we need to communicate in the controller, which is generally a relatively simple communication mechanism, telling the companion controller that something you care about has changed. What should we do? If you are a javascript programmer, you will naturally think of asynchronous callback and responsive communication-event mechanism (or message mechanism ). Yes, this is angularjs's solution to communication between controllers. the only method recommended is angular way. Angularjs provides a bubble and tunnel mechanism for us in scope. $ broadcast broadcasts events to all sub-controllers, while $ emit transmits event bubbles to the parent controller, $ on is the event registration function of angularjs. With this function, we can quickly solve communication between angularjs controllers in angularjs mode. 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);
- $scope.$emit("Ctr1NameChange", name);
- };
- }).controller("childCtr2", function ($scope) {
- $scope.$on("Ctr1NameChangeFromParrent",
-
- function (event, msg) {
- console.log("childCtr2", msg);
- $scope.ctr1Name = msg;
- });
- });
Here, the name change of childCtr1 will be passed to the parent controller in bubble mode, and the parent controller will encapsulate the event in broadcast to all sub-controllers, while childCtr2 registers the change event and changes itself. Note that the parent controller must change the event name during broadcast. Jsfiddle link: http://jsfiddle.net/whitewolf/5JBA7/15/
This article from the "wolf" blog, please be sure to keep this source http://whitewolfblog.blog.51cto.com/3973901/1179536