SARAN SARAN - 29 days ago 6
AngularJS Question

In Angular JS $scope variable value assign from $http

I'm new to angular js. Here i have the code: I receive the response data like number. In this code how i assign the response data as $scope.vote_counting. In this code does not return anything.

$scope.votes = function(){
var votes = $http({
method: "post",
url: "/getVotes",
data: { id: $scope.Id}
}).success(function(response){
});
return votes;
}


Please anyone help to this.

Answer

Simply call the $http. It does not have to be in a function

$http({
    method: "post",
    url: "/getVotes",
    data: { id: $scope.Id }
}).then(function(response) {
    //handle success
    $scope.votes_counting = response.data;
}, function(error){
    //handle error
});

The sort version is

$http.post("/getVotes", { id: $scope.Id }).then(function(response) {
    //handle success
    $scope.votes_counting = response.data;
}, function(error) {
    //handle error
})

Note : You are using a POST method but a GET method seems more appropriate in your case (getVotes)

Comments