From Angular: Transforming local variables into global variables

I am having trouble retrieving the country name from a JSON file outside of its scope. I have tried using $rootScope but without much success. My goal is to use the country name as a variable in different scopes and on the page itself. Additionally, I need to send it to a database using Controller.cs (.net).

app.controller('PageController',
  function ($scope, $http) {

var analyticsCountry = "default";

$.getJSON('//www.geoplugin.net/json.gp?jsoncallback=?',

function (data) {
    $scope.testing = data;
    $scope.testing.country = data.geoplugin_countryName;
    //console.log($scope.testing.country);
    analyticsCountry = $scope.testing.country;
});

    console.log(analyticsCountry);

    $scope.GetTrendingCDsByCountry = function () {
        $http({
            method: 'Get',
            url: "/CD/GetTrending?id=" + analyticsCountry

        })
            .success(function (data, status, headers, config) {
                $scope.cds= data;
            })
            .error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });

    };  


});

Answer №1

To display it on the screen, simply link it to $scope and you're good to go. As mentioned by @Suren Srapyan, the callback will run after the console.log() with the value of "default".

app.controller('PageController',
  function ($scope, $http) {

$scope.analyticsCountry = "default";
$scope.GetTrendingCDsByCountry = function () {
    $http({
        method: 'Get',
        url: "/CD/GetTrending?id=" + $scope.analyticsCountry

    })
        .success(function (data, status, headers, config) {
            $scope.cds= data;
        })
        .error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error';
        });

};  

$.getJSON('//www.geoplugin.net/json.gp?jsoncallback=?',

function (data) {
    $scope.testing = data;
    $scope.testing.country = data.geoplugin_countryName;
    //console.log($scope.testing.country);
    $scope.analyticsCountry = $scope.testing.country;
    console.log($scope.analyticsCountry);
    $scope.GetTrendingCDsByCountry();
  });

});

Now everything should be functioning correctly and accessible from the view.

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

responding to a forum comment in jquery by either replying or quoting

I'm attempting to develop a forum "quote" feature, similar to reply options on many forums. However, I am struggling with selecting the appropriate items from my comment and dealing with dynamically generated IDs. Here is the HTML of my comment: & ...

Utilizing Npm modules with a jQuery plugin

As a newcomer to Npm packages (coming from Ruby), I am attempting to load a jQuery plugin that is not available on NPM. My task involves building a Chrome extension. The code snippet below is utilized in the content.js script that is injected into the brow ...

Make sure to update the package.json file at multiple locations following the execution of the "npm i" command

My goal is to automatically detect any newly installed packages based on my package.json file. This way, whenever I run "npm i", the new package will be added not only to the usual "dependencies" section but also to a custom section called "extDependenci ...

Sending JSON information between activities using AsyncTask

My goal is to read a JSON file and pass its data to another Activity by creating a ListView. However, I am unsure of where exactly I need to set the Intent. This code snippet shows the SplashScreen where I retrieve the JSON: public class SplashScreen exte ...

The presence of an additional bracket is being triggered by the JSON array following

Currently, I am developing a function in Freemarker to iterate through all selected checkboxes and then display the same response on the form itself. The form is structured in Freemarker format, and I am utilizing JavaScript to create separate arrays for e ...

Converting UK DateTime to GMT time using Angular

I am currently working on an angular project that involves displaying the start and end times of office hours in a table. For instance, the office operates from 8:30 AM to 5:30 PM. This particular office has branches located in the UK and India. Since u ...

Gather JSON information through a combination of JQuery ajax(), PHP scripting, and MySQL database interaction within a

I've been searching high and low with no luck. Here's what I'm dealing with: Utilizing Custom PHP MVC and attempting to achieve the following: I want to replace the id="ShowName" in userView.php with JSON data fetched via an Ajax call using ...

How do I utilize the emit() method in the Alexa-SDK to retrieve and return multiple objects within a JSON array?

I am facing an issue with the emit() method in the Alexa-SDK while trying to retrieve multiple account id's from a JSON array. The problem is that it is only emitting one of the values instead of both. How can I modify the emit() method to return both ...

What is the best way to reverse an EJS forEach loop?

Here is my ejs code to display images and names from my database. How can I reverse the array order to show the images and names in reversed order? <% posts.reverse().forEach(function(post){ %> <div class="col-md-3 col-sm-6"> ...

Steps for importing JSON data into MongoDB via Mongoose

Currently facing some challenges with this task, here's the situation... Using Mongoose and MongoLab for data storage and retrieval works smoothly. However, I am looking to implement a system that can initialize the database with base seed data. The ...

Unraveling intricate nested JSON data: A comprehensive guide

I need assistance with an Android application that displays information about railways between two stations. I am trying to retrieve railway data from the railwayapi to showcase on the Android app. However, I am facing challenges in converting the JSON dat ...

What are the steps for integrating connect-multiparty into route paths?

I am looking to incorporate connect-multiparty into my routes. Upon researching, I found the following example... var multipart = require('connect-multiparty'); var multipartMiddleware = multipart(); app.post('/upload', multipartMiddle ...

Steps for generating tab panels and their respective content using a v-for loop

I am currently utilizing Vue 3 in combination with Bootstrap 5. My objective is to incorporate multiple Tabpanels within a v-for. Each of these Tabs should feature distinct content. To achieve this, I attempted placing my Tabs and their respective Conten ...

Interactive elements within $ionicLoading

I am attempting to create a clickable button within the $ionicLoading template. I need to execute some code when that button is clicked. Unfortunately, it seems like ng-click is not working. Is there a workaround for this issue? Or am I making a critical ...

The ng-if directive seems to be causing issues within an ng-repeat loop when used in conjunction with bind-html

Below is the code I am using to bind html in my webpage: <div bind-html-compile="menuButtonView"></div> This is the code in my controller: dashboardService.getTemplateMetaData(data.templateCategory) .success(function(data) { console.lo ...

How can I access the contents of queryParams when performing a redirect with Router.navigate?

When I redirect, I attempt to pass information through queryParams so it can be processed in the destination. However, I am encountering an issue where queryParams are empty. ngOnInit(): void { this.activatedRoute.queryParams.subscribe(({ token }) => ...

What's the simplest method for updating a single value within a nested JSON object using TypeScript?

Using TypeScript version ^3.5.3 Consider the following JSON data: const config = { id: 1, title: "A good day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" } To update the title using spread synta ...

My simple application is experiencing a problem where ComponentDidMount is not being invoked

I used a tool called create-react-app to build this simple application. Strangely, the ComponentDidMount method is never getting invoked. import React, { Component } from "react"; class App extends Component { componentDidMount() { console.log("M ...

The process of exporting and utilizing models in Sequelize

When working on my node.js project with sequelize, I encountered a challenge of exporting and using table models in another file. I typically save table models in a folder, for instance Profile.js. module.exports = (sequelize, DataTypes) => sequelize.d ...

Issues with Angular routing not accepting request parameters

As I attempt to navigate to a partial template upon form submission in Angular using ng-view, I encounter an issue with passing parameters through the URL. Specifically, I am trying to pass a parameter ?username=Joe and retrieve it in the new partial using ...