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?
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.
The is two ways to do this:
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
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!');
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With