Vercaelus Vercaelus -5 years ago 97
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.

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

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

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

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

Answer Source

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


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'];

        .then(function (response) {

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download