Angularjs服务回调以更新控制器的范围

时间:2013-09-21 10:46:03

标签: angularjs angularjs-scope

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

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 page

{{mService.data.somedata}}

问题:

m3rdPartLib.on()是第三方库回调函数,我在服务中使用它。我希望在ui中显示它,因为它正在更新。在回调时,值会发生变化,但不会反映在ui上。

阅读一些文档,发现$ rootScope。$ apply可以调用,但我没有在服务中引用$ scope / $ rootScope。

4 个答案:

答案 0 :(得分:26)

您可以依赖$rootScope并在您的服务中调用apply。

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

答案 1 :(得分:3)

我需要更新服务中的输入字段,因为它有监听器以及那些没有随机动态更改数据的内容。

这也可用于调用控制器中的范围函数:

//scope will be set to current scope of a controller
//which has an ng-view containing this element    
var scope = angular.element('#input-element').scope();
//wrap changes in an apply call to make sure view and model are consistent
scope.$apply(function() {
    scope.object.data = value;
});

感谢此帖:How do I access the $scope variable in browser's console using AngularJS?

答案 2 :(得分:0)

使用$scope.$watch功能。看看我的jsfiddle。我没有你的库,所以我只模拟它 - 5秒后值从0变为1。

答案 3 :(得分:0)

如果您在服务中使用范围,则表明您打破SRP是一个很好的指示,因为您的服务应该只检索控制器的数据。 我的建议是你可以做这样的事情。

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

mbAppModule.controller({
  MController: function ($scope, $http, mService) {
  this.GetPartLib = function (){ 
    mService.on('timeupdate', function() {
     this.data.somedata=1;
    });
  }
});