是否可以将控制器中的范围变量注入服务函数Angular?

时间:2016-05-04 14:09:48

标签: javascript jquery angularjs

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

        }]);

我这里有一个带有2个函数的服务,我需要以某种方式修改getStations函数以允许使用以下内容:

$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[]=");
        }
};

我需要将$scope.filterList附加到此处:

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

原因是我必须在提交搜索按钮时进行新的$ http调用。我希望我的描述性足够。

1 个答案:

答案 0 :(得分:2)

没有。您不能在服务中注入$ scope。在您的服务中公开所需的方法,并将所需的数据(在您的范围内)作为参数传递。从控制器中的更改方法调用服务方法。

<强>服务

this.getStations = function(filterList){
              return $http.get(baseURL+"station.json"+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[]=");
          }
stationsService.getStations($scope.filterList);
}