0

I need to pass the value of a $scope variable from my angular controller to my angular factory, where this value is further being used to do other calculations.

Controller :

angular.module('myApp').controller('MyController',['$scope', function($scope)
{
    $scope.selectedValue = function(value)
   {
      $scope.valueToSend = value + 1000;
   }
}]);

Factroy:

angular.module('myApp').factory("Factory", ["$q","$localStorage", function(q, $localStorage)
{
   var functionToGetValue = function()
   {
    return value;
   }
}
var x = { .... }
return x;
}]);

The 'value' in my controller is simply a radio button that is been selected. Within my factory, the variable x has other functions that call my factory function functionToGetValue.

Is there some way I can pass $scope.valueToSend to my factory so that I can further use it there itself??

2
  • what is wrong with passing value to factory and then return its update to the controller? Commented Jan 13, 2017 at 11:12
  • I am not sure how to pass that value to the factory, and I want to avoid using $rootScope. Commented Jan 13, 2017 at 11:14

2 Answers 2

2

Have a setter/getter method in your factory with which you can set the new value and when you want to reuse it , use the same method to get it as shown below :

angular.module('myApp').factory("Factory", ["$q","$localStorage", 

function(q, $localStorage)
{ 
   this.value = "";
   return {
    inputValue : function (value) {
       if(value)
         this.value = value;
       else
         return value;
    }   
  }
}
var x = { .... }
return x;
}]);

Now, from you controller,

angular.module('myApp').controller('MyController',['$scope', 'Factory'

function($scope, factory)
{
    $scope.selectedValue = function(value)
     {
      $scope.valueToSend = value + 1000;
       factory.inputValue($scope.valueToSend); // this will set the new value in the factory.
     }

console.log(factory.inputValue()) // this will get the value from the factory.

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

Comments

1
angular.module('myApp').factory("Factory", ["$q","$localStorage", function(q, $localStorage)
{
   var value;
   var x = {
     setValue = function(val) {
         value = val;
     };
     functionToGetValue = function()
     {
        return value;
     }
   }
   return x;
}]);

Create factory like the above code and use that factory in your controller. use Factory.setValue(valueToPass) and Factory.functionToGetValue() to get value passed value back.

Comments

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.