I have encountered an issue where I want to access the single_video variable outside of the controller function in my AngularJS application. It seems to be working fine and printing correctly in the first console.log statement. However, when attempting to access it in the second console.log statement outside of the controller function, I am getting an error saying that single_video is undefined. As someone who is still learning JavaScript and AngularJS, this has been quite confusing for me.
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);