Reputation: 33
I am new to Angular and would like to learn how to accomplish this task I have a dropdown that contains a list of LotType. When a Lot type is selected.I want to make an HTTP GET call to a web API method which returns the list of Lots according to the selected Type
My 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);
}]);
my 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>
Upvotes: 2
Views: 326
Reputation: 3746
The getLots function in you service needs to return a promise and then defer the value which you get by making the $http call. In your controller use .then to wait until the http call is over and then bind the data to your scope variable.
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);
}]);
EDIT
I have created a fiddler for the solution. Check it here. I can't make a $http call from Fiddler so I have mocked the data. The data is getting binded in the select dropdown.
Upvotes: 1
Reputation: 5116
The problem is the service doesn't have access to the scope of the controller (as should be since services should be used by any controller in need). Instead you should return the promise returned by http.get:
factory.getLots=function(selectionType{
return $http.get('http://localhost:8080/planification/lots/',
{ params: { "type":selectionType } });
}
Then on the controller use the data:
$scope.lots = lotsFactory.getLots().success(function(data) {
$scope.lots=data;
});
Upvotes: 2