Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for async data before rendering a list on AngularJS and Ionic

I am a newbie on Angular JS but have good experience working with Javascript.

In my App I am creating a simple Factory fulfilled by JSON data coming from a web service:

.factory('Tools', function($http) { 
    var tools = {content:null};
    var promise = $http.get('/Tool/GetTools').success(function(data) {
        tools.content = data;
        //At this points all the data is on tools.content
    });    
    return {
        promise:promise,
        all: function(){
            return tools;
            //At this point tools equals to null
        }
    }
});

But when I want to render the list:

<ion-list>
      <ion-item ng-repeat="tool in tools">
        Hello, {{tool}}!
      </ion-item>
    </ion-list>

The info isn't still there yet.

I have this on my controller:

.controller('AccountCtrl', function($scope, Tools) {
  $scope.tools = Tools.all();
});

Is there a way to tell the list to "wait" while the Tools object loads from the ajax call before the list renders?

Thanks!

like image 675
Multitut Avatar asked Jan 22 '15 07:01

Multitut


1 Answers

You have to return from your factory the promise and into controller you can check the success. Something like this: (i've simulated the wait with a timeout)

angular.module('App', [])

.controller('Ctrl', function($scope, resultsFactory) {
  
  $scope.results = [{txt: 'Loading..'}];
  resultsFactory.all().then(
    function(res){
      $scope.results = res;
    },
    function(err){
      console.error(err);
    }
  );
})

.factory('resultsFactory', function($http, $timeout, $q) { 
  var results = {};  
  
  function _all(){
    var d = $q.defer();
      $timeout(function(){
            d.resolve([{txt:'one'},{txt:'two'},{txt:'three'}]);
     }, 2000); 
  
    return d.promise;       
  }
  
  results.all = _all;
  return results;
});
<!DOCTYPE html>
<html ng-app='App'>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.20/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div ng-controller='Ctrl'>
    <p ng-repeat='res in results'> {{res.txt}}</p>
  </div>
</body>
</html>
like image 151
hayatoShingu Avatar answered Nov 15 '22 04:11

hayatoShingu