0

I have a Service that listens to webSockets (can't use callbacks or promises, data updates are random). service gets updates and saves them to service's object. I Have an angular-app page with controller that has the service object in the $scope.

But I got a problem in rendering data on the page. Right now I am using $timeout() to update the view but looking for a more elegant way.

I understand that I can use $watch on the service's object, but I think that it is too heavy for browser.

So what is the right way to render the view/controller after changes in service's data?

e-shfiyut
  • 3,538
  • 2
  • 30
  • 31
Axel186
  • 541
  • 5
  • 17
  • you can also use $scope.$apply() but ultimatly going to call watch only.. – Ruhul Aug 19 '16 at 19:33
  • There's not enough information. To optimize things `$scope.$digest()` may be used. It triggers a digest on current scope and nested ones, while any other way triggers a digest on root scope. – Estus Flask Aug 19 '16 at 19:37
  • Sounds interesting! But for calling $digest I need the $scope...? Any way, here is some simple example of my problem: https://plnkr.co/edit/53m5cOe8XDDDRrxFX0NK?p=preview Tried to simulate comming webSockets data with "setTimeout()". I can't work with promises because data pushed.. In service.js you have commented $timeout - if you will uncomment it render will start to work. – Axel186 Aug 20 '16 at 12:08

2 Answers2

0

You can use $rootScope.$broadcast as an alternative but it's also as heavy as $watch, I don't know why you are afraid of using $watch, the cost in performance is not that big !!

To use $broadcast add this line of code to your service :

$rootScope.$broadcast('WatchedData', data);

And in your controller do something like the following :

$scope.$on('WatchedData', function(event) {  return stuff  });

to read more about $rootscope.$broadcast check this SO answer

Community
  • 1
  • 1
ZEE
  • 5,669
  • 4
  • 35
  • 53
  • 1
    I guess broadcast is 'cheaper' than `$watch` because it uses an already-existing listener to `$rootScope`. Am I guessing correctly? – e-shfiyut Aug 19 '16 at 19:40
0

i suggest you to use resolve , it will load data before controller and View is instantianting in your routing file , and inject your Service into function

You can watch this Demo PLunker Demo

Rebai Ahmed
  • 1,509
  • 1
  • 14
  • 21