简体   繁体   English

Javascript 定义全局变量

[英]Javascript Defining Global Variables

I want to use single_video variable in outside of the controller function.我想在控制器功能之外使用 single_video 变量。 It prints well in first console log.它在第一个控制台日志中打印得很好。 However it gives a single_video is undefined error in second console.log which is outside of the controller function.但是,它在控制器功能之外的第二个 console.log 中给出了 single_video is undefined 错误。 I am very poor at both javascript and angularjs.我在 javascript 和 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);

Even single_video is declared, it is not defined, ie it doesn' have defined any value in time of calling second console.log().即使声明了 single_video,它也没有定义,即它在调用第二个 console.log() 时没有定义任何值。

In fact, your first console.log is called later than second, because you just defined some functions, but not called them and therefore didn't set values, sooner than you called your "second console.log".事实上,你的第一个 console.log 比第二个调用晚,因为你刚刚定义了一些函数,但没有调用它们,因此没有设置值,比你调用“第二个 console.log”早。

There is no problem with your variable.你的变量没有问题。 I guess your second console.log is called before the first one.我猜你的第二个console.log在第一个之前被调用。

You should Google "javascript async" or "javascript callback" to understand how asynchronous code works.您应该谷歌“javascript async”或“javascript callback”以了解异步代码的工作原理。

To summarize, when you do "$http.get" you make an HTTP request to a server, which will respond after a certain amount of time.总而言之,当您执行 "$http.get" 时,您会向服务器发出 HTTP 请求,该请求将在一定时间后响应。 When the server responds, your "onSuccess" is called, and your variable is set.当服务器响应时,将调用您的“onSuccess”,并设置您的变量。 Not before.以前不是。

In the meantime, you second console.log will be executed immediately after initializing the HTTP request - so before the server response and the "onSuccess" callback.同时,您的第二个console.log将在初始化 HTTP 请求后立即执行 - 所以在服务器响应和“onSuccess”回调之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM