Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs service callback to update scope of controller

Tags:

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.

like image 477
shrw Avatar asked Sep 21 '13 10:09

shrw


1 Answers

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;         });     }); }]); 
like image 89
Mark Coleman Avatar answered Sep 22 '22 20:09

Mark Coleman