简体   繁体   中英

Why do events from provider not $emit to $rootScope?

To keep things de-coupled in my AngularJS app, I've got a single validationService that different controllers may call to perform the validation. As it is, the validate() method in a given controller should just $emit an event ( request:validate , for example) which the service will listen for -- but it does not appear that $rootScope ever receives the emitted event. For example:

angular.module('mine').controller('CommitController', [
    '$scope',
    function($scope) {
        $scope.validate = function() {
            $scope.$emit('request:validate');
        };
    }
]);
angular.module('mine.services').factory('validationService', [
    '$rootScope',
    function($rootScope) {
        $rootScope.$on('request:validate', function(e) {
            console.log('received the request:validate event - go ahead with validation');
        });
    }
]);

But the $on('request:validate') never fires from $rootScope . Does $rootScope not receive events emitted from child scopes? Is there some quirk in how $rootScope listens to events?

Is there a "more Angular" approach to this? Should the controllers simply call validationService directly? Should the events $broadcast from $rootScope to begin with?

You are not instantiating validationService therefore the listener does not get attached. Include it in the module and inject it to the controller.

angular.module('mine',["mine.services"]).controller('CommitController', [
    '$scope', "validationService",
    function($scope, vs) {
        $scope.validate = function() {
            $scope.$emit('request:validate');
        };
    }
]);
angular.module('mine.services',[]).factory('validationService', [
    '$rootScope',
    function($rootScope) {
        $rootScope.$on('request:validate', function(e) {
            console.log('received the request:validate event -'+
                         'go ahead with validation');
        });
    }
]);

If you don't want to inject the service into controller, you do the binding in module 's run method

angular.module("mine", ["mine.services"]).run(function(validationService){});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM