How to properly communicate between ANGULARJS controllers

Source: Internet
Author: User
Tags emit event listener

The controller in Angularjs is a function used to add additional functionality to the scope ($scope) of the view, which we use to set the initial state for the scope object and to add custom behavior.

When we create a new controller, ANGULARJS will help us generate and pass a new $scope object to this controller, in any part of the ANGULARJS application, there is the existence of the parent scope, the top level is the level of Ng-app, Its parent scope is $rootscope.

Each $scope $root points to $rootscope, $cope. $parent point to the parent scope.

The communication between Cotroller is essentially how the $scope of the current controller communicates with $scope on other controllers.

There are usually 3 solutions in the way:

    • Using the principle of scope inheritance, the sub-controller accesses the contents of the parent controller.
    • Using events in Angularjs, that is, using $on, $emit, $broadcast for message delivery
    • Using the services in ANGULARJS

The first way

That is, scope nesting scope, there are certain restrictions on the use of the scope of nesting, in the actual development of this scenario is relatively small, but not no, this way is simpler and directly.

Angularjs by default, when a property cannot be found in the current scope, it is looked up in the parent scope if it is not found until you find the $rootscope. If the program is still not found in $rootscope, the view is not updated.

Example

Javascript

1 //Javascript2 3App.controller (' Parentcontroller ',function($scope) {4 5$scope. Person = {greeted:false};6 7     });8 9App.controller (' Childcontroller ',function($scope) {Ten  One$scope. SayHello =function() { A  -$scope. Person.name = ' Ari Lerner '; -  the         }; -  -     }); -  +     //HTML -  +<div ng-controller= "Parentcontroller" > A  at<div ng-controller= "Childcontroller" > -  -<a ng-click= "SayHello ()" >say hello</a> -  -</div> -  in {{person}} -  to</div> +  -     //result the  *{"Greeted":true, "name": "Ari Lerner"}

The second way

Because scopes are hierarchical, you can use the scope chain to pass events.

There are 2 ways to pass events: * $broadcast: Events that are triggered to notify the entire event system (allowing any scope to handle the event) will be propagated downward. * $emit: If you want to remind a global module that you need to notify a higher level of scope (for example, $rootscope), you need to pass the event up.

Use $on for event snooping on the scope.

Example

Javascript

1App.controller (' Parentcontroller ',function($scope) {2$scope. $on (' $fromSubControllerClick ',function(e,data) {3Console.log (data);//Hello4         });5     });6 7App.controller (' Childcontroller ',function($scope) {8$scope. SayHello =function() {9$scope. $emit (' $fromSubControllerClick ', ' Hello ');Ten         }; One     }); A  -     //HTML -<div ng-controller= "Parentcontroller" > the<div ng-controller= "Childcontroller" > -<a ng-click= "SayHello ()" >say hello</a> -</div> -</div>

Another problem to say here is the performance of event propagation, $broadcast + $on way to notify all child scopes, there will be performance issues, so we recommend the use of $emit+ $on way, in order to further improve performance, The defined event handlers are freed together when the scope is destroyed.

Using the $emit+ $on requires us to bind the event listener to $rootscope, for example:

Javascript

1 Angular2. Module (' MyApp ')3. Controller (' Mycontroller ', [' $scope ', ' $rootScope ',functionMycontroller ($scope, $rootScope) {4             varUnbind = $rootScope. $on (' Somecomponent.somecrazyevent ',function(){5Console.log (' foo '));6             });7$scope. $on (' $destroy ', unbind);8         }9]);

But this is a bit cumbersome, and when you define multiple event handlers, the whole person is bad, so let's improve

Use the adorner to define a new event binding function:

Javascript

1 Angular2. Module (' MyApp ')3. config ([' $provide ',function($provide) {4$provide. Decorator (' $rootScope ', [' $delegate ',function($delegate) {5Object.defineproperty ($delegate. Constructor.prototype, ' $onRootScope ', {6Valuefunction(name, listener) {7                     varUnsubscribe =$delegate. $on (name, listener);8                      This. $on (' $destroy ', unsubscribe);9                     returnunsubscribe;Ten                 }, OneEnumerablefalse A             }); -             return$delegate; -         }]); the}]);

So when we define the event handler function in the controller:

Javascript

angular    . Module (' MyApp ')    . Controller (function  mycontroller ($scope) {            $scope. $onRootScope (function() {                console.log (' foo ');            }    ]);
Individuals strongly recommend this approach

The Third Way

Using the features of the service singleton pattern in Angularjs, services provide a way to maintain data over the lifetime of an application, communicate between controllers, and ensure data consistency.

We typically encapsulate the server to provide an interface for the application to access the data, or to interact with the data remotely.

Example

Javascript

varMyApp = Angular.module ("MyApp", []); Myapp.factory (' Data ',function() {  return{name:"Ting"}}); Myapp.controller (' Firstctrl ',function($scope, data) {$scope. Data=Data; $scope. SetName=function() {data.name= "Jack"; }}); Myapp.controller (' Secondctrl ',function($scope, data) {$scope. Data=Data; $scope. SetName=function() {data.name= "Moby"; }});

How to properly communicate between ANGULARJS controllers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.