Skip to content Skip to sidebar Skip to footer

Angularjs Broadcast Confusion

I have a question regarding broadcasting to children scope objects. I have the following factory: app.factory('mySharedService', function($rootScope) { var sharedService = {}; sha

Solution 1:

It might happen because parent controller calls service before child controller finished to load. Try to add dummy timeout:

$timeout(function () {
   mySharedService.prepForBroadcast($scope.alerts);
 }, 0);

Working example:

JS

Demo Fiddle

var app = angular.module('myModule', []);

functionParentCtrl($scope, $timeout, mySharedService) {

    console.log('firstCtrl');

    $scope.alerts = "Im alert";

     $timeout(function () {
       mySharedService.prepForBroadcast($scope.alerts);
    }, 0);    


}

functionChildCtrl($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;
});

HTML

<divng-controller="ParentCtrl"><divng-controller="ChildCtrl"><pre>{{alerts}}</pre></div></div>

Post a Comment for "Angularjs Broadcast Confusion"