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?.

2 Answers 2

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

});
Sign up to request clarification or add additional context in comments.

1 Comment

that's the answer i want. i appreciate the Sergey advice.
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.

2 Comments

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?.
stackoverflow.com/questions/14573023/… something like this is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.