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



我是Angular的新手,想学习如何完成这项任务我有一个包含LotType列表的下拉列表。选择批次类型时。我想对web API方法进行HTTP GET调用,该方法根据所选类型返回批次列表

我的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>

问题是服务无法访问控制器的作用域(因为任何需要的控制器都应该使用服务)。相反,您应该返回http.get:返回的promise

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函数需要返回一个promise,然后推迟通过$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);
}]);

编辑
我为这个解决方案设计了一个小提琴手。请在此处查看。我无法从Fiddler进行$http调用,所以我对数据进行了模拟。数据正在选择下拉列表中绑定。

最新更新