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

Issue with content overlapping when hamburger icon is tapped on mobile device

When the hamburger menu is pressed on smaller screens, I want my navbar to cover the entire screen. To achieve this, I included the .push class in my code (see the jQuery and CSS) to trigger when the .navbar-toggle-icon is pushed. However, after implemen ...

Utilizing JQuery toggle feature to display extra content

Having some trouble with my JQuery toggle/collapse function. I added my own class "timelineEventWide" but it's not working as expected. As a JavaScript beginner, could someone please help me with the correct syntax? Thank you! e(".expandAll").toggle( ...

Utilize Protractor Selenium to extract content from a popup window

Having trouble capturing the text from a popup using Protractor with getText? The HTML structure can be found here. This popup only appears for a few seconds before disappearing. Can anyone assist me in retrieving the text from this popup? To retrieve the ...

Are you looking to refresh the Amplify Redirect URL?

Is there a way to update the redirection URI for Amplify signout in the 'aws-exports' file? What steps should be taken to make this change? Can we simply modify the file directly and then execute 'amplify push'? Update After attempti ...

Can you explain the slow parameter feature in Mocha?

While configuring mochaOpts in Protractor, one of the parameters we define is 'slow'. I'm unsure of the purpose of this parameter. I attempted adjusting its value but did not observe any impact on the test execution time. mochaOpts: { re ...

Puppeteer - Issue with Opening Calendar Widget

Problem: Unable to interact with the calendar widget on a hotel website (). Error Message: Node is either not clickable or not an Element Steps Taken (code snippet below): const puppeteer = require('puppeteer') const fs = require('fs/promi ...

Working with Firestore database in React Js may result in an infinite loop

I have connected my React JS app to Cloud Firestore and I am facing an issue with displaying the objects in my JavaScript file. Even though I only have one object in Firestore, it seems to be reading in a loop and I can't seem to identify the cause. ...

What is the best way to retrieve an array of objects from Firebase?

I am looking to retrieve an array of objects containing sources from Firebase, organized by category. The structure of my Firebase data is as follows: view image here Each authenticated user has their own array of sources with security rules for the datab ...

Concealing a column in ngx-datatable Ionic

I am just starting to work with NGX-datatable and I need to populate my data table in my Ionic app with data from Firebase. Here is the format of the JSON returned from Firebase: If I choose not to use the User_id as a column, how can I access the User_id ...

javascript highchart image carousel

I am currently working on a visual chart project using the JavaScript library highchart. After setting up my chart with some dummy data, I am looking to incorporate functionality that allows for triggering an image slide based on the chart data. Specific ...

Clicking on "Ng-Click" will add a fresh row to the table using Angular

Is there a way to insert a new row into a table using ng-click? I currently have the following setup with the data stored in an array. Here is how my array looks. $scope.workflows = [{ Id: 1, Name: "Workflow Page 1", ...

Load the Angular controller only after the service successfully fetches the Swagger API file

My current controller is dependent on a swagger-js enabled api. Unfortunately, the api remains unavailable until the swagger library acquires the swagger sepcification file. I am looking for a way to ensure that the controller only loads once the swagger A ...

Center rotation with THREE.TrackballControls

I'm facing an issue with rotating an object on the scene using THREE.TrackballControls. The rotation is not relative to the object's axis when it's not in the center of the screen - instead, it rotates based on the center of the screen. I at ...

Tips for leveraging async and await within actions on google and API integration

Currently, I am developing an Actions on Google project that utilizes an API. To handle the API calls, I am using request promise for implementation. Upon testing the API call, I observed that it takes approximately 0.5 seconds to retrieve the data. Theref ...

Issue encountered when attempting to remove an element from an array in MongoDB

I'm currently working on removing an item from an array in a MongoDB model that I have created for countries. Below is my Country model: const CountrySchema = mongoose.Schema({ name: { type: String, required: true }, holidays: [ ...

Prevent zooming or controlling the lens in UIWebview while still allowing user selection

Is there a way to disable the zoom/lens on uiwebview without affecting user selection? I'm trying to avoid using "-webkit-user-select:none" in my css. -webkit-user-select:none ...

Select a single radio button containing values that can change dynamically

<input type="radio" on-click="checkDefaultLanguage" id="checkbox" > [[names(name)]] This custom radio input field contains dynamic values and I am attempting to create a functionality where only one radio button can be selected at a time while dese ...

Numerous status buttons with a variety of background colors

There are 3 buttons on the order page: [New Order], [Processing], and [Completed]. When the processing button is clicked, the background of the button should change and the order status will be updated in the database. The [New Order] button will have a ...

Tips for retaining the original size of an image in HTML5 canvas drawImage

function getBase64ImageData(_id) { var canv = document.createElement('CANVAS'); var context = canv.getContext("2d"); var imageElem = document.getElementById(_id); context.drawImage(imageElem, 0, 0); var dataURL = canv.toDat ...

DataTables.Net Buttons not appearing in the interface

I have a basic MVC project that utilizes BootStrap4 and dataTables.Net. When the page loads, an Ajax call is made to fetch data for a table. However, despite following the documentation, I'm unable to get the buttons to display on the page. Everything ...