Search code examples
angularjsangularjs-rootscopeangular-broadcast

How to listen to $rootscope.$broadcast with $scope


My $scope.$on(... doesn't seem to be picking up the broadcast.

I have an interceptor to capture http response errors and broadcast an event that my main controller can react to.

(function () {
    'use strict';

    angular
        .module('app')
        .factory('httpErrorInterceptor', httpErrorInterceptor);

    httpErrorInterceptor.$inject = ['$rootScope', '$q'];

    function httpErrorInterceptor($rootScope, $q) {
        return {
            responseError: function (rejection) {
                var firstDigit = rejection.status.toString().substr(0, 1);

                if (firstDigit === "4") {
                    $rootScope.$broadcast('client_error', rejection);
                }
                else if (firstDigit === "5") {
                    $rootScope.$broadcast('server_error', rejection);
                }

                return $q.reject(rejection);
            }
        };
    }
})();

In my app I am purposely submitting some invalid data to an API and getting an http 400 back.

I can see in Chrome developer tools that $rootScope.$broadcast('client_error', rejection); is being hit.

The problem is that this isn't getting hit:

(function () {
    'use strict';

    angular
        .module('app')
        .controller('main', main);

    main.$inject = ['$scope', '$window', 'authenticationService', 'shoppingBasketService'];

    function main($scope, $window, authenticationService, shoppingBasketService) {
        // Scope functions.
        $scope.$on('server_error'), function (event, error) {
            console.log('handling server_error', error);
        };

        $scope.$on('client_error'), function (event, error) {
            console.log('handling client_error', error);
        };

        ....

        ....

The scope is loaded. Why isn't it reacting to the broadcast?


Solution

  • There might be other errors in code you haven't shown, but your code listening to events is incorrect. It should be:

    $scope.$on('server_error', function(event, error) {
        console.log('handling server_error', error);
    });
    

    Here's a plunkr showing that it works.