简体   繁体   English

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

[英]How do i define a global variable from asynchronous call with angularjs?

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是未定义的错误。 Because of the asynchronousity. 由于异步。

   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);

You can create a function that you invoke inside the success callback passing your variable as a parameter to the function: 您可以创建一个在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);
}

Define your global variables in a factory service and inject the service in your angular controller where ever you need. 在工厂服务中定义全局变量,然后在需要时将服务注入到角度控制器中。 (Note: try to put everything in an IIFE) (注意:尝试将所有内容放入IIFE中)

Global Variables using services, here is an example: 使用服务的全局变量,这是一个示例:

var myApp = angular.module('myApp',[]);
myApp.factory('MySvc', function() {
return {
  name : 'your name'
};
});

and in a controller: 并在控制器中:

function MyCtrl($scope, MySvc) {
$scope.name = MySvc.name;
}

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

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