我想在 Controller 功能之外使用 single_video 变量。它在第一个控制台日志中打印得很好。但是,它在 Controller 功能之外的第二个 console.log 中给出了 single_video is undefined 错误。因为异步。
var single_video;
var app = angular.module('myApp', []);
app.controller('randomVideo', function($scope, $http) {
var onSuccess = function(response){
$scope.video = response.data;
single_video = $scope.video;
//First console.log
console.log('1st ID='+single_video.yt_id);
};
var onError = function(reason){
$scope.error = "There is an error about getting random_video.php";
};
$http.get("http://www.ytmdb.com/ytvideo/api/random_video.php")
.then(onSuccess, onError);
});
//Second console.log
console.log('2nd ID='+single_video.yt_id);
最佳答案
您可以创建一个在 success
回调中调用的函数,将您的变量作为参数传递给该函数:
var app = angular.module('myApp', []);
app.controller('randomVideo', function($scope, $http) {
var onSuccess = function(response){
$scope.video = response.data;
single_video = $scope.video;
//First console.log
console.log('1st ID='+single_video.yt_id);
test(single_video.yt_id);
};
var onError = function(reason){
$scope.error = "There is an error about getting random_video.php";
};
$http.get("http://www.ytmdb.com/ytvideo/api/random_video.php")
.then(onSuccess, onError);
});
function test(a)
{
console.log('2nd ID='+a);
}
关于javascript - 我如何使用angularjs从异步调用中定义全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33879125/