gpt4 book ai didi

$http.get 中的 AngularJS 访问变量

转载 作者:行者123 更新时间:2023-12-02 03:27:11 25 4
gpt4 key购买 nike

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 在您的 promise 毫无疑问地返回之前就已启动。将console.log放入success.

我大概会这样写:

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

getEntries();

此外,如果仍然存在问题,请使用 console.log(data) 并查看您得到的结果。这可能是后端问题。

Here is a plunker 这表明了我的意思。您不需要像以前那样将它包装在一个函数中。 $http.get 已经起作用了。

关于$http.get 中的 AngularJS 访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29734380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com