javascript - 我如何使用angularjs从异步调用中定义全局变量?

标签 javascript angularjs asynchronous

我想在 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/

相关文章:

javascript - 使用 UI 路由器访问从解析函数调用的服务中新状态的 $stateParams

linux - Linux 上真的没有异步 block I/O 吗?

javascript - 异步/等待永远卡住

multithreading - 为什么我在使用 Async.Parallel 时只有一个线程 id?

javascript - knockout : Click button created server side

javascript - 我的 javascript 错误在哪里?转换日期格式

java - Java 和 JS/AS3 之间 URL 解码/编码 UTF-8 的差异(错误!?)

javascript - 使用模态窗口实例在 Angular JS 中保存并下一步

angularjs - $http.post 方法中的 415(不支持的媒体类型)

angularjs - 单击表格行以触发 Angularjs 中的复选框单击