我如何在服务中使用的角度$? [英] How do i use $on in a service in angular?

查看:83
本文介绍了我如何在服务中使用的角度$?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经能够得到控制器上使用监听器的$
$范围。$关于

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.

我试过 $ rootScope。$关于,但只允许一个监听器。我想在多个服务听众,不论其父母是否控制器在范围或没有。

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.

推荐答案

试验公平一点事实证明,让事件服务可以用最少的code完成后。

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

样的服务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;
}]);

这篇关于我如何在服务中使用的角度$?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆