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

查看:28
本文介绍了用于更新控制器范围的 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() 是我在服务中使用的第 3 方库回调函数.我想在 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.$apply,但我在服务中没有 $scope/$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 并在您的服务中调用 apply.

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天全站免登陆