andNn andNn - 3 months ago 38
AngularJS Question

Angularjs service callback to update scope of controller

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


And a controller

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


html page

{{mService.data.somedata}}


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.

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

Answer

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