Arrow Arrow - 7 months ago 9
Javascript Question

Is It possible to inject a scope variable from a controller into a service function Angular?

angular.module('store_locator')
.constant("baseURL","http://locator.sas.dev.atcsp.co.za/api/")
.service('stationsService', ['$http', 'baseURL', function($http,baseURL) {

this.getStations = function(){
return $http.get(baseURL+"station.json");
};

this.getStation = function (index) {
return $http.get(baseURL+"station/"+index+".json");
};

}]);


I have here a service with 2 functions, I need to amend the getStations function in some way to allow the usage of the below:

$scope.filterList = [];
$scope.change = function(subproduct, active){
if (active){
$scope.filterList.push(subproduct.subproduct_id);
$scope.filterPush = "?subproducts[]="+$scope.filterList.join("&subproducts[]=");
}
else{
$scope.filterList.splice($scope.filterList.indexOf(subproduct), 1);
$scope.filterPush = "?subproducts[]="+$scope.filterList.join("&subproducts[]=");
}
};


I need to append the
$scope.filterList
here:

return $http.get(baseURL+"station.json"+$scope.filterList);


The reason for this is that i have to do a new $http call on submit of a search button. I hope I'm descriptive enough.

Answer

No. You cannot inject $scope in your service. Expose the desired method in your service and pass the required data (which is in your scope) as an argument. Call the service method from your change method in the controller.

Service

this.getStations = function(filterList){
              return $http.get(baseURL+"station.json"+filterList);
          };

Controller

$scope.change = function(subproduct, active){
        if (active){
            $scope.filterList.push(subproduct.subproduct_id);
            $scope.filterPush = "?subproducts[]="+$scope.filterList.join("&subproducts[]=");
          }
        else{
            $scope.filterList.splice($scope.filterList.indexOf(subproduct), 1);
            $scope.filterPush = "?subproducts[]="+$scope.filterList.join("&subproducts[]=");
          }
stationsService.getStations($scope.filterList);
}