user2893858
user2893858

Reputation: 41

how to call a service in another module using $on and $broadcast

I'm trying to do a call from factory A to factory B using angular's $broadcast. These two factories are defined in separate modules.. Below is the code that attempts to do this.

angular.module('secondApp', [])
  .service('B', function($rootScope, $scope) {
    $rootScope.$on('test', function(event, data) {
        console.log(event, data);
    });
});

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

app.controller('MainCtrl', function($scope, A) {
    $scope.test = function() {
        A.test();
    };
});

app.service('A', function($rootScope) {
    this.test = function() {
        $rootScope.$broadcast('test', 'Hello from service A!');
    };
});

Upvotes: 4

Views: 1368

Answers (1)

JC.Li
JC.Li

Reputation: 54

You should use $rootScope.$emit() instead of $rootScope.$broadcast().

Because $rootScope.$broadcast() will despatch downwards.

Edit:

Made a sample code to test emit/broadcast/on base on Angular guide: Plunker.

Turns out that using $rootScope.$on to listen event will be triggered by $rootScope.$emit and $rootScope.$broadcast. The difference is $broadcast will dispatch downwards, so all scopes will receive the event also.

So if you just want to notify $rootScope, just using $rootScope.$emit. $rootScope.$broadcast will waste resource.

Hope it will help.

Upvotes: 2

Related Questions