Hugo Nakamura
Hugo Nakamura

Reputation: 483

How to refresh a ng-repeat after the data was received from an external source

Right now I have this html that repeats itself creating a list according to an array of objects.

      <md-list class="proj-list">
        <md-item ng-repeat="it in projects track by it.ProjectID">
          <md-item-content>
            <md-button ng-click="selectProject(it)" ng-class="{'selected' : it === selected }">
              {{it.ProjectID}}
            </md-button>
          </md-item-content>
        </md-item>
      </md-list>

The controller is here:

  $scope.selected = null;
  $scope.projects = allProjects;
  $scope.selectProject = selectProject;
  $scope.toggleSidenav = toggleSidenav;

  loadProjects();

  function loadProjects() {
    myService.loadAll()
      .then(function(projects){
        allProjects = projects;
        $scope.projects = [].concat(projects);
        $scope.selected = $scope.projects[0];
        console.log($scope.projects); 
      })
  }

and the myService:

var request = $http.get('http://localhost:9001/api/descriptions') ;

request.success(function(data, status, headers, config) {
  for(var i=0; i<data.length; i++){
    projects.push(data[i]);
  }
    console.log(projects);
});
request.error(function(data, status, headers, config) {
    alert( "failure message: " + JSON.stringify({data: data}));
});


  return {
      loadAll: function() {
          console.log(projects);  
          return $q.when(projects);
      }
  };

The order that I want the code to be run is: http get the data from server -> loadAll send data to controller -> ng-repeat generates the list on HTML

But what is happening is: ng-repeat generates the list (empty) -> loadAll send data to controller (nothing) -> http get the data from server

What should I do to control the order that my code is executed? I tried the $scope.$apply() command but it says that I already have a $digest or $apply command running but I didn't request any of that.

Upvotes: 0

Views: 171

Answers (1)

Pierre Gayvallet
Pierre Gayvallet

Reputation: 2953

The issue is not where you think it is. The principe of watchers is that the dom is rerendered when the model updates. So your ng-repeat should render a first time, empty, at initial digest before your ajax call returns to the client, then a second time when $scope.projects is filled.

The real problem is in your service. You seems to have an issue understanding how promises works. With your current code, Your service's loadAll method resolve instantly with an empty list.

return {
  loadAll: function() {
    return $http.get('http://localhost:9001/api/descriptions').then(function(response) {
      return response.data
    })
  }
};

should works a lot better.

Upvotes: 1

Related Questions