如何收听$ rootscope。$ $ with $ scope

时间:2016-04-17 11:18:01

标签: angularjs angularjs-rootscope angular-broadcast

我的$scope.$on(...似乎没有接收广播。

我有一个拦截器来捕获http响应错误并广播我的主控制器可以做出反应的事件。

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

在我的应用程序中,我故意向API提交一些无效数据并返回http 400。

我可以在Chrome开发者工具中看到$rootScope.$broadcast('client_error', rejection);正在被点击。

问题是这不会受到影响:

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

        ....

        ....

已加载范围。为什么不对广播作出反应呢?

1 个答案:

答案 0 :(得分:2)

您未显示的代码中可能存在其他错误,但您监听事件的代码不正确。它应该是:

std::vector

这是a plunkr showing that it works

相关问题