簡體   English   中英

在Angular JS中,$ scope變量值從$ http賦值

[英]In Angular JS $scope variable value assign from $http

我是angular js的新手。 我在這里有代碼:我收到像數字這樣的響應數據。 在這段代碼中,我如何將響應數據分配為$ scope.vote_counting。 在此代碼中不返回任何內容。

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

請任何人對此提供幫助。

只需調用$http 它不必在函數中

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

排序版本是

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

注意:您使用的是POST方法,但是GET方法似乎更適合您的情況( getVotes

我添加了一個片段,顯示了對Promise的基本處理。 在這里,我使用了一種服務來模擬http調用。 響應附加到范圍變量,該變量在視圖中顯示。

 angular.module('TestApp', []) .factory('MockHttp', function($q) { return { getMockData: function() { return $q.when(['A', 'B', 'C']); } }; }) .controller('TestController', function($scope, MockHttp) { $scope.res = null; MockHttp.getMockData() .then(function(res)  { $scope.res = res; }) .catch(function(err) { console.log(err); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="TestApp"> <div ng-controller="TestController"> {{res}} </div> </div> 

$ http函數不返回服務器的響應。 但是,您已經知道可以使用成功函數來獲取服務器響應。 只需在成功函數中設置$scope.votes值,如下所示:

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

最簡單的方法可能是使用$ http.post 請注意,不贊成使用then來支持success

$scope.retrieveVotes = function(){
  $http.post('/getVotes', {id : $scope.id}).then(function(response){  
    $scope.votes = response.data;
  });
}

還要注意, $http調用是異步的,因此調用retrieveVotes也是異步的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM