我想在控制器功能之外使用single_video变量。它在第一个控制台日志中打印良好。但是它给出了single_video是第二个console.log中的未定义错误,它在控制器函数之外。由于异步性。如何从angularjs异步调用定义一个全局变量?
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);
你打成什么作为*“第二console.log“*实际上是第一个console.log。你所要求的是根本不可能的。 “second”console.log将永远无法为您提供该值。 –
@KevinB他们是一样的,但我得到了第二个“未定义”的错误。第二个console.log在single_video由于异步定义之前打印。有没有办法使用回调函数等等。我的jacascript背景非常差。 – Tahtakafa
在回调运行后,您必须访问全局变量**。因此,访问全局变量的代码必须位于回调中或从回调中调用。但是,现在不需要全局变量了。 –