Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notify of changes between controllers that may or may not exist

If you have two area's on a page, i.e

<div ng-controller="LeftController">

</div>

<div ng-controller="RightController">

</div>

And lets say the LeftController can live and exist without the RightController. But should the RightController exist and something change ... then the LeftController needs to know about that change.

How can the LeftController know subscribe to those changes? Does that require a framework like Amplify or is this something that can be handled in Angular?

Usecase

So the problem I'm solving is theres some tabs on the screen. The user may or may not have access to either tabs.

When the tab is loaded initially, it loads from the server.

Tab 2 (RightController) may load before Tab 1 (LeftController), if Tab 1 doesn't exist or isn't loaded yet, and Tab 2 publishes a change. Nothing happens. If Tab 1 is loaded, user goes to Tab 2, changes a value, that may affect the UI in Tab 1. So Tab 2 publishes that hes changed. Tab 1 now changes what he needs based on the new information.

like image 649
Phill Avatar asked Oct 22 '13 10:10

Phill


2 Answers

The is two ways to do this:

  1. Using events (emit or broadcast in the scope)
  2. Using a Service / Factory

I've made a plunker with these 2 options. I hope it help you.

Plunker - Example

Sources:

http://docs.angularjs.org/api/ng.$rootScope.Scope http://docs.angularjs.org/guide/dev_guide.services.creating_services

like image 138
Deividi Cavarzan Avatar answered Oct 21 '22 22:10

Deividi Cavarzan


You can create a simple service and inject it to both controllers.

app.factory('myService', function() {
    var onMessageCallbacks = [];
    var onMessage = function(cb) {
        onMessageCallbacks.push(cb);
    };

    var newMessage = function(msg){
        for (var cb in onMessageCallbacks) {
            onMessageCallbacks[cb](msg);
        }
    };

    return {
        onMessage: onMessage,
        newMessage: newMessage
    };
});

First, you use onMessage to subscribe to events:

app.controller('LeftController',
    function LeftController($scope, myService) {
        myService.onMessage(function(receivedMsg){
            // do sth...
        });
    }
);

When one of the controllers wants to say something, use newMessage:

app.controller('RightController',
    function RightController($scope, myService) {
        myService.newMessage('Hello!');
    }
);
like image 30
lort Avatar answered Oct 21 '22 21:10

lort