Anton
Anton

Reputation: 7719

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

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 events.

I tried $rootScope.$on, but that only allows one listener. i want listeners in multiple services regardless of whether their parent controllers are in scope or not.

Upvotes: 34

Views: 31773

Answers (2)

Mark Rajcok
Mark Rajcok

Reputation: 364697

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.

Upvotes: 12

Anton
Anton

Reputation: 7719

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

Upvotes: 47

Related Questions