Angularjs服务回调以更新控制范围 [英] Angularjs service callback to update scope of controller

查看:123
本文介绍了Angularjs服务回调以更新控制范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与第三方库的回调函数服务:

A service with a 3rd party library callback function:

mbAppModule.service('aService', function ($http) {
    this.data={"somedata":0};
    var m3rdPartLib="init";  // init    
    m3rdPartLib.on('timeupdate', function() {
        this.data.somedata=1;
    });
}

和控制器

mbAppModule.controller({
    MController: function ($scope, $http, mService) {
        $scope.mService= mService;    
    });
});

html页面

{{mService.data.somedata}}

问题:

m3rdPartLib.on()是我使用它的服务的第三方库的回调函数。我想在UI中显示它,因为它是得到更新。回调值得到改变,但在UI上没有得到体现。

PROBLEM :

m3rdPartLib.on() is a 3rd party library callback function which i am using it in a service. I want to show it in the ui as it is getting updated. On callback the value is getting changed, but not getting reflected on ui.

看了一些文档,发现$ rootScope。$应用可以调用,但我没有$范围的参考/ $ rootScope的服务。

Read some docs and found $rootScope.$apply could be called, but i don't have the reference of $scope / $rootScope in the service.

推荐答案

您可以在 $ rootScope 的依赖,并调用适用于您服务。

You can take a dependency on $rootScope and call apply in your service.

mbAppModule.service('aService', ["$http", "$rootScope", function ($http, $rootScope) {
    this.data = {
        "somedata": 0
    };
    var m3rdPartLib = "init"; // init    
    m3rdPartLib.on('timeupdate', function () {
        $rootScope.$apply(function(){
            this.data.somedata = 1;
        });
    });
}]);

这篇关于Angularjs服务回调以更新控制范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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