Search code examples
angularjsrootscope

passing data from controller to service in angularjs


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


Solution

  • 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());
    }]);