使用 $http 服务和 ng-change 从服务器获取数据并将其显示在 select 事件上

get Data from server and display it on select event using $http service and ng-change

我是 Angular 的新手,想了解如何完成此任务 我有一个包含 LotType 列表的下拉列表。当批次类型为 selected.I 时,想要对 Web API 方法进行 HTTP GET 调用,其中 returns 根据所选类型

的批次列表

我的app.js

app.factory('LotService',['$http',function($http){
    var factory={};
    factory.getLots=function(selectionType){
      $http.get('http://localhost:8080/planification/lots/',{
        params:{
          "type":selectionType
        }
      })
       .success(function(data){
          Lots=data;
        })
    }
    return factory;
}]);

app.controller("ExampleController",['$scope','LotService',function($scope,LotService){

  $scope.Types=['particulier','admin','indus'];
  $scope.getLots=function(selectionType){
    $scope.Lots=LotService.getLots(selectionType);
  }
  $scope.getLots(selectionType);
}]);

我的index.htm

<div class="form-group">
    <label class="col-sm-3 control-label">Type client</label>
    <div class="col-sm-9">
        <select class="selectpicker form-control" multiple ng-model="test.type" ng-change="getLots(test.type)">
          <option ng-repeat="type in Types" value="{{type}}">{{type}}</option>
        </select>
    </div>
</div>
<div class="form-group">
    <label class="col-sm-3 control-label">Lot </label>
    <div class="col-sm-9">
        <select class="selectpicker form-control" ng-model="test.lot">
          <option ng-repeat="lot in Lots" value="{{lot}}">{{lot}}</option>
        </select>
    </div>
</div>

问题是服务无法访问控制器的范围(应该是因为服务应该由任何需要的控制器使用)。相反,你应该 return return 由 http.get:

编辑的承诺
factory.getLots=function(selectionType{ 
   return $http.get('http://localhost:8080/planification/lots/',
       { params: { "type":selectionType } });
} 

然后在控制器上使用数据:

$scope.lots = lotsFactory.getLots().success(function(data) { 
   $scope.lots=data; 
});

您服务中的 getLots 函数需要 return 一个承诺,然后延迟您通过 $http 调用获得的值。在您的控制器中使用 .then 等待 http 调用结束,然后将数据绑定到您的范围变量。

app.factory('LotService',['$http' '$q',function($http, $q){
    var factory={};
    factory.getLots=function(selectionType){
    var defer = $q.defer();
      $http.get('http://localhost:8080/planification/lots/',{
        params:{
          "type":selectionType
        }
      })
       .success(function(data){
          defer.resolve(data)
        })
    return defer.promise;
    }
    return factory;
}]);

app.controller("ExampleController",['$scope','LotService',function($scope,LotService){

  $scope.Types=['particulier','admin','indus'];
  $scope.getLots=function(selectionType){
    LotService.getLots(selectionType).then(function(data) {
    $scope.Lots = data;
})
  }
  $scope.getLots(selectionType);
}]);

编辑
我为解决方案创建了一个提琴手。检查一下 here。我无法从 Fiddler 进行 $http 调用,所以我模拟了数据。数据在 select 下拉列表中绑定。