Search code examples
angularjsbroadcastangularjs-rootscope

Angular Broadcast not working


I am unable to broadcast to other controllers as I have no parent child relation ship therefore, using $rootScope to broadcast the change to other controllers.

Please help me to identify the problem in code.

function serverController( server, $state, $rootScope, $timeout)
{
    var vm  = this;
    vm.loader = false;

    (function tick() {
        server.setRootScope().then(
            function(response){
                angular.forEach(response.data, function (val) {
                    val['serverState'] = (val.status == 'running')?true:false;
                    $rootScope.servers[val.id] = val;
                });
                vm.servers = $rootScope.servers;
                $rootScope.$broadcast('serverUpdated', [1,2,3]);
                console.log('serverUpdated', [1,2,3]);
            }
        );

        $timeout(tick, 25000);
    })();
}


function serverManageController(server, $state, $rootScope, $stateParams)
{
    var vm  = this;
    $rootScope.$on('serverUpdated', function(event, mass) {
        console.log('serverUpdated');
        console.log(mass);
    });
}

Solution

  • Modify tick function like this.

     function tick() {
        server.setRootScope().then(
            function(response){
                angular.forEach(response.data, function (val) {
                    val['serverState'] = (val.status == 'running')?true:false;
                    $rootScope.servers[val.id] = val;
                });
                vm.servers = $rootScope.servers;
                $rootScope.$broadcast('serverUpdated', [1,2,3]);
                console.log('serverUpdated', [1,2,3]);
            }
         );
      };
    
     $timeout(function(){
       $interval(tick, 25000);
     },2000);
    

    and it should work as you expect.