The 'this' variable is malfunctioning when trying to assign a JSONP array to an AngularJS controller

I'm working with a REST service in my angular controller and using JSONP to make the call. I need to store the array that is returned from the service into a variable.

This is what I currently have:

this.testTheRest = function()
{
    $http.jsonp('myRESTService', {
            params: {
                callback: 'JSON_CALLBACK',
                format: 'json'
            }
        })
            .success(function (data) {
                this.testlist = data.NoParamsResult;
                console.log(this.testlist);
            })
            .error(function (data) {
                alert(data);
            });

        console.log(this.testlist);
}

I have already declared testlist as an empty array in the controller:

this.testlist = [];

There are two console output calls in the code. The issue I'm facing is that the first one correctly displays the array:

Array [ Object, Object ]

However, the second one shows an empty array, most likely the initialized one:

Array [  ]

What changes do I need to make in order to retain the objects returned by the service in the array?

Thank you for your assistance,
Frank

Answer №1

The issue here is related to scoping. One possible solution is to store the value of the outer this in a new variable, such as that, and then use that variable instead of this.

var that = this;

that.fixTheProblem = function() {
    $http.jsonp('myRESTApi', {
        params: {
            callback: 'JSON_CALLBACK',
            format: 'json'
        }
    })
    .success(function(data) {
        that.result = data.successResponse;
        console.log(that.result);
    })
    .error(function(data) {
        alert(data);
    });
}

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

Node-static is reporting that the localhost page cannot be located

I am currently attempting to serve static files using node-static. My plan is to eventually run this as a Windows service using nssm. I have successfully executed this process in the past, however for some reason it is not working now. Here is the code sn ...

Error: The function **now.toUTCString** is not recognized and cannot be executed by HTMLButtonElement

While the JavaScript code runs smoothly without setting a time zone, I encountered an error when trying to display the Barbados time zone. The issue is related to now.toUTCString function throwing the following error message. How can I resolve this? Uncau ...

Creating pagination in Vue using an array of objects

I'm new to Vue and arrays and I need help paginating my json array so that only 10 items are displayed per page. Currently, all the items in the array are being shown in the <tr> body. I've tried different methods without success. Can someo ...

Looping through an array in Angular with ng-repeat

In my controller, I have managed to loop through the primary xml-based data successfully. However, I am facing challenges in passing the secondary child data (in the second level tr tag where I want all "list" categories to repeat) within the loop. angula ...

numpy offers the ability to create distinct slices for each layer of an array

Given a 3D array m*n*k, I need to extract subarrays of size i*j from each 2D layer. There is an array c containing the starting coordinates for these slices in each layer (with a size of 2*k). Is there an efficient way to achieve this without utilizing loo ...

Tips on how to eliminate items from a list that do not include a specific character

I need help with a list that has a specific format /listing/vasita-otomobil-volkswagen-boyasiz-2016-passat-variant-1.6-tdi-dsg-higline-sunroof-hayalet-819608311/detail,#,#,,/listing/vasita-otomobil-volkswagen-boyasiz-2016-passat-variant-1.6-tdi-dsg-higline ...

Retrieve both the name and id as values in an angular select dropdown

<select (change)="select($event.target.value)" [ngModel]="gen" class="border border-gray-200 bg-white h-10 pl-6 pr-40 rounded-lg text-sm focus:outline-none appearance-none block cursor-pointer" id="gend ...

Execute JavaScript code once the XMLHttpRequest has completed execution

I'm facing an issue where the JavaScript code is executing faster than the XMLHttpRequest. I am hesitant to resolve it using: setTimeout(function() {}, 100); Below is a snippet of my code: function change_country(id) { if (window.XMLHttpReques ...

Navigating manually in ui-router with AngularJS 1.7 is ineffective

A state configuration within my application is as follows: function stateConfig($stateProvider) { $stateProvider .state("home", { url: "/", templateUrl: "/app/home/template/home.html", controller: "HomeContr ...

Receiving no communication from Express Router

Having trouble receiving a response from the server after making get/post requests. I've tried adjusting the order of functions in index.js without success. I also attempted to send a post request using Postman to localhost:8080/register, but the requ ...

What is the best way to enlarge text size with jquery?

I am attempting to: $('a[data-text="size-bigger"]').click(function () { a=$('span'); b=$('span').css('font-size'); a.css('font-size', b+1); } ); Initially, I ha ...

Tips for displaying HTML content using an array in Vue JS

Hi, I'm a beginner with Vue JS and I'm working on passing an HTML table using this array. I have a dropdown where I can select the option I want, but I'm struggling to figure out how to include HTML within it. Whenever I try, it ends up disp ...

What is the best way to deactivate a button when not all inputs require filling?

I need to make a change in my form where I want to disable a button, but not all the inputs are mandatory. Even though I have specified which inputs need to be filled in the code, I still have to fill all the inputs in the form. How can I modify this? $ ...

Streamline jQuery code for dynamically populating two select dropdowns

I am looking to streamline and enhance this script to make it more dynamic. There could be multiple items in options, potentially even up to ten items. In the current scenario, the maximum number of items allowed is 2. The total value selected across both ...

Utilizing Javascript to Open a New Tab from Drupal

I'm attempting to trigger the opening of a new tab when a specific menu link is clicked within a Drupal website. My initial approach was to incorporate JavaScript directly into the content of the page, but unfortunately this method has not been succes ...

data retrieval not refreshing sorting post construction

My challenge involves fetching data from MongoDB with sorting. While it works perfectly on the development server, it fails to update the data after being built and hosted. import Review from "@/models/review"; import connectdb from "@/util/ ...

Is there a way to configure the text box to allow for range values input?

Is there a way to create an input box that only accepts values between 20 and 40? I want to restrict single numbers within that range. How can I define the range for this specific input box? If anyone can help me achieve this, it would be greatly apprecia ...

When a new VueJS project is created, it failed to automatically install the necessary basic HTML files and folders

Hey there, I am completely new to Vue.js. Just recently, I installed the Vue.js/CLI and created a brand new project using vue create test. This prompted me to choose from three options: > Default ([Vue 2] babel, eslint) Default (Vue 3 Preview) ([Vue 3 ...

Execute iMacros Loop and terminate the process before proceeding to the next command

As a newcomer to the world of iMacro scripting, I am struggling with setting up a simple data scrape. I'm looking for guidance on how to create a loop for the following commands: URL GOTO=link1 URL GOTO=link2 URL GOTO=link3 WAIT SECONDS=7.5 Once th ...

Display scrollable content at the bottom

I am currently working on creating a chat application using JavaScript (AngularJS without jQuery) and I am wondering if it is possible to have a scrollable div load to the bottom automatically. While I am familiar with the scrollTo JS property, I do not f ...