2016-04-18 31 views
2

我是Angular的新手,並且想要了解如何完成此任務 我有一個包含LotType列表的下拉列表。當許多類型是selected.I想使一個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返回大量的列表中的網絡API方法

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

回答

2

問題是服務沒有權限訪問控制器的範圍(應該是因爲服務應該被任何需要的控制器使用)。相反,你應該返回由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; 
}); 
+0

感謝您的回答 – hind

1

在您服務的getLots函數需要返回一個承諾,然後推遲值你可以通過$ http調用獲得。在你的控制器中使用。然後等到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調用,所以我嘲笑了數據。數據被綁定在選擇下拉菜單中。

+0

非常感謝您的回答,我可以從服務器獲取數據並將其顯示爲段落,但我無法在