What is the best way to declare a global variable while making an asynchronous call using AngularJS?

Is there a way to utilize the single_video variable outside of the controller function? The issue arises when attempting to access it in the second console.log, as it returns an 'undefined' error due to asynchronousity despite successfully printing in the first console log.

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

Answer №1

To incorporate your variable into a function called within the success callback, you can follow this example:

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

Answer №2

To ensure global variables are accessible throughout your Angular application, create a factory service to define them and then inject the service into any controller where they are needed. Remember to encapsulate everything in an IIFE for better code structure.

Here is an example of defining global variables using services:

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

And here's how you can access this variable in a controller:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

center text above images in flexbox when page is resized

When resizing the page, I'm facing an issue where the links overlap with the images in a flexbox layout. It seems like the padding and margin between the images and links are not working due to them not being "related" or connected. I believe I need t ...

How can I execute JavaScript within a for loop in the server-side code?

protected void Button1_Click(object sender, EventArgs e) { for (int i = 0; i < 100; i++) { Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScript", "<script>alert('hello world');</script>"); } } Is th ...

What is the best way to combine relative paths or create distinct identifiers for SVG files located within multiple layers of folders

I have a collection of icons exported from "Figma" organized in folders, and I'm using grunt-svgstore to create a sprite sheet. However, the result contains duplicated IDs even after trying 'allowDuplicateItems: false' and 'setUniqueIds ...

Choosing a specific option utilizing ng-options is a straightforward process

My journey begins with an array of various sources $scope.sources = [ { "type": "register", "name": "Register 1", "balance": 100 }, { "type": "register", "name": "Register ...

Unending cycle when integrating AngularJS with Laravel

I am struggling with an issue while integrating ngRoute with Laravel framework. Within my routes.php file: App::missing(function($exception) { return File::get(public_path() . '/angular.html'); }); This is the content of my angular.html fi ...

Looking for a way to streamline data transfer using script setup in Vue 3? Consider utilizing composables to simplify the process

In the scenario where there is a parent component labeled as "1" with two child components named "2" and "3", each of these components containing its own child component, "4" for "2" and "5" for "3", the challenge arises on how to pass state from child c ...

Have I potentially compromised my project by executing the command `npm audit fix --force`?

While working on a React project using Vite, everything was going smoothly. I decided to incorporate some charts and came across the recharts package, which I found quite appealing. So, I added it to my project using the command npm i recharts. After runn ...

Enhanced hierarchical organization of trees

I came across this code snippet: class Category { constructor( readonly _title: string, ) { } get title() { return this._title } } const categories = { get pets() { const pets = new Category('Pets') return { ge ...

Executing a function that includes showModalDialog outside of an iframe might display the incorrect page

This website structure looks like: `--main.html `--dialog.html `--folder `--iframe.html The code for each page is as follows: main.html: <html> <head> <script type="text/javascript"> function t ...

Pressing a button triggers the highlighting of a tab in HTML through the use of Javascript

In the corner of my webpage, I have three tabs: info, question, order. When I click on one tab header, only that tab should highlight. The info section includes two buttons that link to the question and order tabs. When these buttons are pressed, the respe ...

The URL may change, but the component remains constant when navigating back

My application consists of two primary components: the Project component and MainContainer. The MainContainer component regularly fetches data using a fetchData method. When moving forward, both the URL and component can change dynamically. However, when m ...

Navigating through the maze of ES6 imports and dealing with the complexities

Currently, I am delving into React and creating my own components. However, the issue of project organization has arisen. Here is the structure of my project: Project_Folder - Components - Form - index.js - form.less - package.js ...

Looking for a dynamic solution to retrieve over 100 data products in Angular JS? Let's explore methods to efficiently call a large volume of

Just starting out with Angular JS and working on creating a searchable product list gallery using Angular JS. Currently, all my product data is in the same js file which I know isn't the best solution. I would like to make it dynamic by connecting to ...

Is it possible to display CKEditor5 toolbar buttons in a separate row rather than the primary row?

https://i.stack.imgur.com/Tyfqb.png I successfully integrated CKEditor5 into my create react app directly from the source code. However, I am facing an issue where the overflowed buttons in the toolbar are being displayed in a separate menu item instead o ...

Mongoose sparks a confrontation following the preservation of a single document in the database

I'm struggling to understand what minor mistake I'm making in this code. I have simplified the user schema to just one property, which is name. Initially, when I post the first entry to the database, it gets saved without any issues. However, whe ...

Update the contents of TubeBufferGeometry with a new TubeBufferGeometry directly, avoiding unnecessary memory allocation

I am working with a mesh that is based on a TubeBufferGeometry. In each animation cycle, the path of the TubeBufferGeometry needs to change based on values provided at runtime. To achieve this, I want to update the geometry with a new TubeBufferGeometry ev ...

Updating a document on Firestore based on a query is a straightforward process that involves first identifying

I'm currently working on a web form page that needs to update input fields into a specific firestore document based on certain conditions. Can anyone provide guidance on how this can be achieved? The initial part where I retrieve the query results se ...

Unable to view iframe's HTML content on Edge and Internet Explorer browsers due to compatibility issues

This code belongs to my Angular application. <div class="with-border" layout="column" flex> <iframe class="no-pointer-events" flex ng-attr-srcdoc="{{vm.campaign.body | toTrustedHTML}}" width="100%" frameborder="0" sandbox="allow-scrip ...

Develop a Vue.js component embedded within another component to manipulate data stored in the parent

After reviewing a few answers that partially address my question, I realized there is more to explain. In our Laravel project website layout, we utilize a global #app div. This means all pages share the same main Vue instance, prompting me to segregate ke ...

Unable to execute Javascript function within a click event handler

I am encountering an issue with a div that is loaded through ajax. Here is the structure of the div: <div id="container"> <a href="#" class="easyui-linkbutton submit_data">Click here to submit</a> </div> Within the same file c ...