AngularJS factory not working

Problem

I have abstracted my working code from a controller into a factory, but it doesn't seem to be working and I can't find what's wrong. I opted for a factory rather than a service because I wanted to execute some code that defined the variable before returning that variable; I want to get result.station (a part of the data returned by the API), not the full result.

This is my code:

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

app.factory('api', ['$http',
  function($http) {
    var station_list = [];
    $http({
      method: 'GET',
      url: 'http://api.irail.be/stations/?format=json&lang=nl'
    })
      .success(function(result) {
        station_list = result.station;
      });

    return {
      Stations: function() {
        return station_list;
      }
    };

  }
]);

app.controller("myController", ['api', '$scope',
  function(api, $scope) {
    $scope.station_list = api.Stations();
    $scope.title = "Stations";
  }
]);

and a working example.

Problem courtesy of: Ben

Solution

You had a small error, you were replacing the array instead of populating it. I used angular.copy instead of the assignment in your factory and it works

http://plnkr.co/edit/sqgKcFZAcClmkfdXHhrz

Solution courtesy of: shaunhusain

Discussion

Try this:

.success(function(result) {
    angular.copy(result.station, station_list);
});
Discussion courtesy of: Ye Liu

The problem is that you are dealing with asynchronous nature of AJAX.

I would suggest to have a delegate method in controller, which will be called when the service call is complete.

Something like the following:

app.controller("myController", ['api', '$scope',
  function(api, $scope) {
    api.Stations( function(station_list) {
      $scope.station_list = station_list;
    });
    $scope.title = "Stations";
  }
]);

The following is a service method excerpt:

return {
  Stations: function(delegate) {
    if (delegate)
      delegate(station_list);
    return station_list;
  }
};
Discussion courtesy of: Vladimir Roytman

This recipe can be found in it's original form on Stack Over Flow.