I've been thinking about this topic for a while and I've seen most of the threads pertaining to communication between controllers. It's simple to share data between controllers, I built out this simple fiddle to demonstrate what I've managed to understand so far.
JS fiddle link - http://jsfiddle.net/fb3qyuat/2/
Code Snippet
var myApp = angular.module('myApp',[]);
myApp.controller('Ctrl1', ['$scope', 'shareData', function($scope, shareData) {
$scope.person = {
name: 'Joe',
age: '35',
occupation: 'Pizza Chain Owner'
};
$scope.changeData = function(data) {
shareData.setData(data);
};
$scope.getData = function(data) {
$scope.person = shareData.getData();
};
}]);
myApp.controller('Ctrl2', ['$scope', 'shareData', function($scope, shareData) {
$scope.person = {
name: 'Dr Dre',
age: '30',
occupation: 'Rapper'
};
$scope.changeData = function(data) {
shareData.setData(data);
};
$scope.getData = function(data) {
$scope.person = shareData.getData();
};
}]);
myApp.controller('Ctrl3', ['$scope', 'shareData', function($scope, shareData) {
$scope.changeData = function(data) {
shareData.setData(data);
};
$scope.getData = function(data) {
$scope.person = shareData.getData();
};
}]);
myApp.factory('shareData', function() {
var shareData = {};
shareData.setData = function(dataEntered) {
shareData = dataEntered;
};
shareData.getData = function() {
return shareData;
};
return shareData;
});
Where I get confused is what is the best way to notify other controllers that rely on this new and updated data. I know some ways of doing this but a developer friend of mine is very against GOTO events ($broadcast, $on, $emit).
Is there any other way of notifying a particular controller about a change in data when another controller updates the data?
Follow up question: If event based notification is really the only legitimate option where is the best place to handle the $broadcast or $emit. Inside of the service using the $rootscope (sounds like a no-no) or inside the controller after updating the data.