ANGULARJS communication between controllers, event notification Service

Source: Internet
Author: User

Service to keep in mind is that all services are singleton (singleton), service is more to do some business logic, data interaction. Of course, the use of a single example of this feature can also be used to do communication between different controllers. There are several ways to communicate between controllers: How do ANGULARJS controller controllers communicate?

The way in which scope inheritance is leveraged. That is, the child controller inherits the content from the parent controller

Event-based approach. namely $on, $emit, $boardcast these three ways

Service mode. Write a single example of a service and then inject it to use

The first is somewhat limited, the second is not very convenient (or personal), and the service implements the event-based notification method.

On the Code
//provides communication to different controllersApp.factory ("EventService",function () {    varOneventfunc = {}; return{on:function(type, f) {//Event BindingsOneventfunc[type] =F; }, Trigger:function(type, data) {//Triggering Events             for(varIteminchOneventfunc) {                if(Item = =type) Oneventfunc[item] (data); }        }    }}); //UsefunctionTest1controller (EventService) {Eventservice.on ("Newmess",function(data) {//console.log (data);    });}functionTest2controller ($scope, EventService) {$scope. Send=function(data) {//Here is an example of what I used in the project when a new message was sent notifying the other controller         //triggering events, notifyingEventservice.trigger ("Newmess", data); }}

Can be based on this idea to expand the implementation of more complex business.

ANGULARJS communication between controllers, event notification Service

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.