Reputation: 55
The situation is like the code below. I want to change the value of $scope.pizzaList and $scope.selectedPizza when calling a function, but it seems not to change. I guess it is something with $scope's depth, but I'm not getting it. How to make these values get updated? Thanks in advance!
$scope.pizzaList = "some initial value";
$scope.selectedPizza = "some initial value";
$scope.setPizzaStatus = function (setStatus) {
$http.post('url1', { userID: $scope.pizzaioloID, pizzaID: $scope.selectedPizzaID, statusNum: setStatus }).
then(function(response) {
$http.get("url2")
.success(function (response) {
$scope.pizzaList = response;
});
$http.get("url3")
.success(function (response) {
$scope.selectedPizza = response[0];
});
}, function(response) {
console.log("Error");
});
}
$scope.pizzaList // doesn't get updated
$scope.selectedPizza // doesn't get updated
Upvotes: 0
Views: 372
Reputation: 11190
The way your code is written I would not expect the value of $scope.pizzaList to have changed between when you set it and when you evaluate it at the end. It will only be changed when you call the setPizzaStatus() method, and even then it will only change after the post to url1 and the get from url2 have returned from your server.
Upvotes: 2
Reputation: 2745
Try use $q.all():
$q.all([
$http.get("url2"),
$http.get("url3")
]).then(function(values){
$scope.pizzaList = values[0];
$scope.selectedPizza = values[1];//or values[1][0], It depends on data format;
}, function(error){
//error processing;
});
Don't forget add $q
service to controller;
Upvotes: 4
Reputation: 17
When you make a Get request, your Javascript code enters in "another task". So sometimes the current scope is not updated as expected. Try update the scope by calling "Apply", like this:
$http.get("url2")
.success(function (response) {
$scope.pizzaList = response;
$scope.$apply(); //or $scope.$applyAsync();
})
Upvotes: -2