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

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

Leave a Comment