Vercaelus Vercaelus - 4 months ago 9
Ajax Question

How can I update an Angular controller after an AJAX API call?

I'm creating a weather forecast app, using ng-repeat to iterate on my forecast.dayArray to create the different days in the page.

The issue is that the controller used to fill in the data in each "day" isn't being updated with the information that is parsed from the ajax API call. Instead, it just keeps whatever value it was initialized with.

//Initialize
var app = angular.module("weather", []);

app.controller("ForecastController", function(){
this.array = ['a','b','c'];
});

ajaxCall(){
success: function(){
app.controller.array.push('d'); //Doesn't seem to work
};


You can see the code in its entirety here: My Codepen

Answer

In your example, app.controller is a function that is used to set up a new controller, so in this line:

app.controller.array.push('d');

app.controller is not a reference to your "ForecastController".

A simple way to fix this would be to make the AJAX call from within the controller, facilitated by the $http service:

app.controller("ForecastController", ["http", function ($http) {
    this.array = ['a', 'b', 'c'];

    $http
        .get(...)
        .then(function (response) {
            this.array.push('d');
        });
}]);

While this will work, it is typically considered better practice to separate the data fetching into its own service and inject that new service into your controller.