How do i use $on in a service in angular?

前端 未结 2 1457
半阙折子戏
半阙折子戏 2020-12-01 01:45

i have been able to get controller to use the $on listener with $scope.$on.

but i don\'t see any documentation on how to get services to listen for even

相关标签:
2条回答
  • 2020-12-01 01:55

    Since $on is a scope method, you could create a scope in your service, then listen for events on it:

    app.factory('myService', function($rootScope) {
        var scope = $rootScope.$new();  // or $new(true) if you want an isolate scope
        scope.$on('testEvent', function() {
            console.log('event received');
        })
        return {}
    });
    
    function MyCtrl($scope, myService, $rootScope) {
        $rootScope.$broadcast('testEvent');
    }
    

    fiddle

    However, I would not recommend this approach, since scopes are not normally associated with services.

    0 讨论(0)
  • 2020-12-01 02:10

    after experimenting a fair bit it turns out that getting events to the service can be done with minimal code.

    sample service code follows in case anyone else runs into this.

    The sample saves and restores the service model to local storage when it gets the respective broadcasts

    app.factory('userService', ['$rootScope', function ($rootScope) {
    
        var service = {
    
            model: {
                name: '',
                email: ''
            },
    
            SaveState: function () {
                sessionStorage.userService = angular.toJson(service.model);
            },
    
            RestoreState: function () {
                service.model = angular.fromJson(sessionStorage.userService);
            }
        }
    
        $rootScope.$on("savestate", service.SaveState);
        $rootScope.$on("restorestate", service.RestoreState);
    
        return service;
    }]);
    
    0 讨论(0)
提交回复
热议问题