簡體   English   中英

$ http.get內的AngularJS訪問變量

[英]AngularJS access variable inside $http.get

app.controller('EntryCtrl', ['$scope', '$http', function($scope, $http){
    $http.get(something.json).success(function(data){
      $scope.entries = data;
    });
    abc = $scope.entries.timestamp;  <-- not working
}]);

搜索之后,發現$ http是一個異步函數。 所以我將它包裝到一個函數中,但仍然無法正常工作。

app.controller('EntryCtrl', ['$scope', '$http', function($scope, $http){
    var getEntries = function(){ return
      $http.get(something.json).success(function(data){
        return data;
      });
    };

    $scope.entries = getEntries();
    console.log($scope.entries); // returns undefined
}]);

你的console.log在你的承諾毫無疑問地返回之前就開始了。 將console.log置於成功之中。

我可能會這樣寫:

var getEntries = function(){ 
      $http.get(something.json).success(function(data){
        $scope.entries = data;
        console.log($scope.entries);
      });
    };

    getEntries();

此外,如果它仍然存在問題,console.log(數據),看看你得到了什么。 這可能是一個后端問題。

這是一個說明我的意思的傻瓜 你不應該像你一樣將它包裝在一個函數中。 $ http.get已經是函數。}

暫無
暫無

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

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