AngularJS Live Example
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div ng-controller="ParentCtrl">
<div ng-controller="ChildCtrl">
<pre>{{alerts}}</pre>
</div>
</div>
JavaScript
var app = angular.module('myModule', []);
function ParentCtrl($scope, $timeout, mySharedService) {
console.log('firstCtrl');
$scope.alerts = "Im alert";
$timeout(function () {
mySharedService.prepForBroadcast($scope.alerts);
}, 2000);
}
function ChildCtrl($scope, mySharedService) {
console.log('secondCtrl');
$scope.alerts = [];
$scope.$on('handleBroadcast', function () {
$scope.alerts = mySharedService.alertArray;
});
}
app.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.alertArray = [];
sharedService.prepForBroadcast = function(alertArray) {
this.alertArray = alertArray;
this.broadcastItem();
};
sharedService.broadcastItem = function () {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});