Search code examples
javascriptangularjsangularjs-factory

Wrong value of scope in angular controller


I am new to angular 1, and I have problem with my code:

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

app.factory("competitions", ['$http', function($http) {
  return $http.get("json/competitions.json")
  .success(function(response) {

    var data = {
      response: response,
      teams: []
    };

    for (var i = 0; i < response.length; i++) {

      $http.get("json/teams.json")
      .success(function(response2) {
        data.teams.push(response2);
        return data
      })
      .error(function(err) {
        return err;
      });
    }

  })
  .error(function(err) {
    return err;
  });
}]);


app.controller('MainController', ['$scope', "competitions", function($scope, competitions) {
  competitions.success(function(data) {
    $scope.competitions = data;
  });
}]);

I want to pass data from competitions factory to $scope.competitions in MainController. After last iteration of for loop data variable should be passed to the controller. I know this code is wrong, beacuse it passes only response to controller, but I don't know how to fix it. Could someone help me?


Solution

  • You're doing a few things wrong here.

    1. The .success() and .error() functions are not used anymore. Use .then() instead.

    2. The .success() function has four parameters. The first one is the data that is returned, so response is the actual data, not the whole response. If you use .then(), then you'll get the response back, which you can extract data out of.

    3. Use the $q library to return your own promise rather than returning data from a factory. You can extract that data in your controller, as you should.

    4. Don't run a loop off of response directly, since you never know if it'll be an array or not. If it's an actual response, it'll be a wrapper around the actual data.

    5. Where's the returned data and err from the teams.json promise going? I'd guess that that part's empty.

    6. Promises take eons to resolve compared to code, so I'd advise you to not call the teams.json from the factory, but from the controller. That is, substitute a dummy inside an ng-repeat in your scope, then when this data comes back, put the actual data in place of the dummy.