-2

I am new to angular js.

I need to access data from my controller to service.

I tried using $rooyScope but my service needs to be loaded first and then my controller so using $rooyScope gives me error.

so i am unable to get the data stored in $rooyScope on service.

Can any suggest me a options that suits my expectation

Thank you for your help

Rohan Kawade
  • 453
  • 5
  • 18
  • Service should be independent of the controller data. If you want that service with some variable configurable then you can use providers. Could you please explain why do you need to access controller data in service? Sample code will work – Manoj Shevate Oct 19 '15 at 16:56

1 Answers1

0

Use functions in the service to set a service variable

angular.module('myServiceModule', []).
factory('testService', function() {
   var myVariable;
   return setVariable: function(parameter) {
       myVariable = parameter;
       // DO SOMETHING ELSE IF YOU WANT
   },
   return getVariable: function() {
       return myVariable;
   }
 });

then in your controller inject the service and call the service function

angular.module('myControllerModule', []).
controller('testController, ['testService', function(testService) {
     testService.setVariable('TEST');
     console.log(testService.getVariable());
}]);
David
  • 153
  • 7