AngularJS array not refreshing following an AJAX request

Currently, I am still in the process of familiarizing myself with Angularjs and actively learning about its functionalities.

One issue I have encountered is that when I define an array and loop through it using "ng-repeat," the items within ng-repeat fail to update after a function is executed. An example of this can be seen in the following jsfiddle.

http://jsfiddle.net/ematevosyan/t3ruzytk/8/

function MyCtrl($scope) {

    // initializing google maps auto complete input
    var options = {
        types: ['(cities)']
    },
    input = document.getElementById('searchTextField'),
        autocomplete = new google.maps.places.Autocomplete(input, options);

    // sample array
    $scope.testArray = [{
        name: 'item1'
    }];

    // function to test a push into array
    $scope.testPush = function () {
        $scope.testArray.push({
            name: 'item2'
        });
    }

    // change listener for google input autocomplete
    $scope.inputChanged = google.maps.event.addListener(autocomplete, 'place_changed', function () {

        // storing the location in a variable
        $scope.specificLocation = autocomplete.getPlace().formatted_address;
        //alert($scope.specificLocation);

        $.ajax({
            type: 'GET',
            url: 'https://api.github.com/repos/bvasko/Bootstrap-Select-Box',
            async: false,
            contentType: "application/json",
            dataType: 'jsonp',

            success: function (data) {
                alert(data);
                $scope.testArray.push({
                    name: $scope.specificLocation
                });
            }, 

            error: function (e) {
                console.log(e.message);
            }


        }); // end ajax call



    });


}

In the provided example, you can observe that the button functions correctly by pushing a new item into the array and updating the ng-repeat. However, after entering a location in the input field and updating the array, the new item is added to the array but does not reflect in the ng-repeat. I am striving to achieve real-time updates in the ng-repeat as soon as a user inputs a location.

I have attempted solutions such as utilizing Angular's $http instead of $ajax and implementing $apply, but unfortunately, neither of these approaches yielded the desired outcome. I suspect there might be a simple solution that I am overlooking, but I am unable to pinpoint it at the moment.

Answer №1

Give it a shot:

Don't forget to call $scope.$apply() after adding the object to the array.

According to the official documentation:

"$apply() is crucial for running expressions in Angular from external sources like browser DOM events, setTimeout, XHR, or third-party libraries. Since we are interacting with the Angular framework externally, it is important to follow the correct scope life cycle and handle any exceptions while also executing watches."

Check out more information here$rootScope.Scope#$apply

JSFiddle link: Visit the JSFiddle demo here

Answer №2

A more angular-friendly approach is to utilize $http instead of $.ajax and $apply. Your attempt with $http is the way to go:

$http.jsonp('https://api.github.com/repos/bvasko/Bootstrap-Select-Box?callback=JSON_CALLBACK')
    .then(function (response) {
        $scope.testArray.push({
            name: $scope.specificLocation
        });
    });

Check out the updated fiddle here

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

Utilizing Ajax to serialize or transfer JSON objects

I have received a Json object and I am looking to extract the data using JavaScript. Specifically, I need help with looping through fields and extracting the data. def For_Sale_Listing(request,id): try: listing = Listing.objects.filter(pk=id) ...

What is the best way to access the attributes of a particular object following a triggered event?

I'm a bit unsure if my title makes sense, so allow me to explain. In a nutshell, I have 2 li elements within a ul list. What I aim for is that when one of these li elements is clicked, the text within that particular li is retrieved, and then an obje ...

What is preventing me from using bracket notation with a variable to assign a property to an object?

I am a complete beginner when it comes to Vuex, and I am currently facing an issue with assigning a value to a Vuex state, specifically state.map.status.isReady. To make my code more reusable, I decided to create a function called changeMapStatus(state, k ...

Transferring the link value to an AJAX function when the onclick event is triggered

I have a link containing some data. For example: <li><a href="" onclick="getcategory(this);"><?php echo $result22['category']; ?></a></li> I need this link to pass the value of $result22['category']; to ...

What is the best way to format a lengthy SQL query as a JavaScript variable?

I have a lengthy SQL query that needs to be converted into a JavaScript variable. The contact information is spread across separate rows using the + character. However, the SQLite plugin is displaying a parsing error: What is the correct way to format t ...

Generating numerous responses in Node (sails js) from a solitary function

Currently, I am facing an issue while developing a web application using AngularJS and Sails. The problem arises in my application's menu section where different count values are supposed to be displayed from the database. When I try to retrieve this ...

Issues with displaying HTML video content

Seeking assistance with a unique coding predicament. I've got an HTML file that showcases a JavaScript-powered clock, but now I'm looking to enhance it by incorporating a looped video beneath the time display. Oddly enough, when the clock feature ...

CSS Navigation Bar Fails to Function Properly on Mobile Devices

Check out the plunkr I have created by visiting: http://plnkr.co/edit/gqtFoQ4x2ONnn1BfRmI9?p=preview The menu on this plunkr functions correctly on a desktop or laptop, but it doesn't display properly on a mobile device. I suspect that the issue may ...

Encountering an error message stating 'click' property is undefined when implementing Java Script Executor in Selenium

I encountered an issue: Cannot read property 'click' of undefined when attempting to click a button using JavaScript executor. Despite trying multiple approaches such as action classes and WebDriverWait, I have been unable to successfully click ...

Creating arrays in JavaScript with or without the use of jQuery

In my JavaScript script, I am defining this array: var status=[ { "name":"name1", "level":0 }, { "name":"name2", "level":0 }, { "name":"name3", "level":0 }, { "name":" ...

I'm sorry, but your request to access the API from the React localhost has been hinder

Currently, I am delving into the world of React, a JavaScript framework. My task involves fetching a token from an API provided by this service: . To achieve this, I must include my X_CONSUMER_KEY in the request. Here is the approach I am taking using the ...

Is there a way to ajax multiple forms simultaneously?

I'm facing an issue with my PHP code that generates multiple forms: <?php while($result = $mods->fetch()) { echo "<form><input type='text' name="variable-name" /><input type='submit' name='submit&apos ...

Finding it challenging to retrieve the dynamically generated data from the PHP-MYSQL combination through jQuery AJAX

The question's title doesn't provide much information. Let me explain what I'm trying to accomplish here. Using jQuery, I have an HTML form that sends an AJAX request to a PHP file. The PHP file successfully returns the required data back to ...

Tips for styling a React JS component class

I am attempting to write inline CSS for a React JS component called Login, but I keep encountering an error. What could be causing this issue? Could you provide guidance on the correct way to implement in-line component CSS? import React, {Component} from ...

Having trouble updating a text field on an event using JavaScript - value not defined

When I change the select option, my goal is to dynamically set the value of the input using JavaScript. However, I am encountering an issue where the value becomes undefined. Below is a snippet from my HTML (JSP) file: <body> <center>< ...

Sequelize Error: The WHERE parameter for 'email' is throwing an error due to an invalid value of 'undefined'

Currently, as part of my Node.js application, I am using Sequelize to develop a user registration feature. However, I seem to be facing an issue when attempting to verify the existence of a user based on their email address. The error that keeps popping up ...

How can I resolve the issue of not returning anything ondrop in my code?

Whenever I drop my div containing an image, I don't see anything. And when I try to access its ID, I get a null value. How can I extract information from a div with an image and append a row with it? For code samples or to check the codepen example, v ...

Displaying a SQL table with AJAX based on radio button selection

I am facing an issue with my webpage where I have three radio buttons and an empty table. The objective is to select a radio button and display a list of employees in the table based on the selection. However, the list does not appear when I click the butt ...

Easily linking a React app to MongoDB

I recently developed a basic react app using 'create-react-app'. The app includes a form, validation, and Bootstrap components. It may not be extravagant, but it functions flawlessly. Furthermore, I registered with MongoDB to obtain a compliment ...

Ways to retrieve a specific value from a JSON dataset

I currently have an Ajax live search script with multiple text inputs for searching products. The live search functionality works perfectly, but I have a query: If I decide to change the name of a product, how can I go back to the previous page and re-s ...