javascriptangularjsangularjs-scopeangular-broadcast

Angular broadcast event causing listener to execute two times


I have a method in a service which broadcasts an event and one controller has subscribed for it.

When broadcast happens the subscriber handler executes two times. Below is the setup:

//Broadcaster

function (Id1, Id2, Id3) {
    var requestObj = {"ID1": Id1, "ID3": Id3};
    $http.post(url, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    })
    .success(function (response) {
        $rootScope.$broadcast('myevent');
    }).error(function (response) {
    });
}
================================================================

//subscriber

$scope.$on('myevent', function () {
    console.log($dialog); // Executes two times
});

I am not able to rectify the cause. Is there something else which can make the difference. Thanks.


Solution

  • As it turns out there was multiple declaration of controller which was causing duplicate $on to trigger.

    One of the common reason this happens is due to controller declared in the $routeProvider configuration and also in the view html using ng-controller