2

i need to following code to access service instance variable inside the $rootscope.

myapp.service('myservice',function($rootScope)
{

  this.var = false;
  $rootScope.$on('channel',function(e,msg)
  {
     var = true;
  });
});

how can i access myservice.var inside the $rootscope.$on?.

nsa
  • 199
  • 1
  • 7

2 Answers2

2

Leaving out the bad\best practice debate about using $rootScope, you can access your variable like this:

myapp.service('myservice',function($rootScope) {

  var me = this;
  this.myVar = false;

  $rootScope.$on('channel',function(e,msg) {
     me.myVar = true;
  });

});
haimlit
  • 2,572
  • 2
  • 22
  • 26
1

This problem you try to solve it's kinda have smell of bad approach. In your case you already have $rootScope in your service so you can write something like:

$rootScope.var = false;

and this will be absolutely same level $rootScope abuse as yours current attempt. But services are something that made to avoid of using $rootScope that way. Best way to do it quick and dirty is something like this.

But better way is to call method on service not emitting event on $rootScope.

Community
  • 1
  • 1
Sergey Moiseev
  • 2,953
  • 2
  • 24
  • 28
  • ok i will explain the situation. i have websocket service which is receiving messages from backend at anytime .when ever the message received to websocket service it's broadcast those messages.listening messages from controllers not possible since controllers destroyed when view changes,so some messages can be lost. so what option do i have?. – nsa Jun 15 '14 at 11:12
  • http://stackoverflow.com/questions/14573023/is-binding-objects-to-angulars-rootscope-in-a-service-bad/23998262#23998262 something like this is better. – Sergey Moiseev Jun 15 '14 at 11:14