Multitut Multitut - 7 months ago 165
AngularJS Question

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 {
all: function(){
return tools;
//At this point tools equals to null

But when I want to render the list:

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

The info isn't still there yet.

I have this on my controller:

.controller('AccountCtrl', function($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?



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..'}];
      $scope.results = res;

.factory('resultsFactory', function($http, $timeout, $q) { 
  var results = {};  
  function _all(){
    var d = $q.defer();
     }, 2000); 
    return d.promise;       
  results.all = _all;
  return results;
<!DOCTYPE html>
<html ng-app='App'>
<script src="//"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <div ng-controller='Ctrl'>
    <p ng-repeat='res in results'> {{res.txt}}</p>