Search code examples
javascriptangularjsangular-resource

Update ng-repeat after ng-resource call is finished


I am using ngResource in combination with ng-repeat and noticed that slow REST calls doesn't update the list properly. It keeps empty.

As far as I understood I need a binding between controller and ng-repeat element.

My resource and controller definition:

(function (configure) {
    configure('loggingResource', loggingResource);

    function loggingResource($resource, REST_CONFIG) {
        return {
            Technical: $resource(REST_CONFIG.baseUrl + REST_CONFIG.path + '/', {}, {
                query: {
                    method: 'GET',
                    isArray: true
                }
            })
        };
    }
})(angular.module('loggingModule').factory);

(function (configure) {
    configure('logController', logController);

    function logController(loggingResource) {
        var that = this;
        loggingResource.Technical.query(function (data) {
            that.logs = data;
        });
        //that.logs = loggingResource.Technical.query();
    }
})(angular.module('loggingModule').controller);

ng.repeat usage:

<tr class="table-row" ng-repeat="log in logController.logs">

What I have tried so far:

  • ng-bind in combination with ng-repeat
  • $q with deferrer
  • $promise of ngResource

What did I miss?

My try to get it on plnkr: https://plnkr.co/edit/t1c5Pxi7pzgocDMDNITX


Solution

  • The {{}} provides a default binding between your controller and view and you don't need to add anything explicitly. I have updated your plunkr with some minor changes to injected constants etc. and it is working.

    // Code goes here
    angular.module("loggingModule", ['ngResource']);
    
    (function(configure) {
      configure('loggingResource', loggingResource);
    
      function loggingResource($resource) {
        return {
          Technical: $resource('https://api.github.com/users/addi90/repos', {}, {
            query: {
              method: 'GET',
              isArray: true
            }
          })
        };
      }
    })(angular.module('loggingModule').factory);
    
    (function(configure) {
      configure('logController', logController);
    
      function logController(loggingResource) {
        var that = this;
        that.logs = [{
          title: 'test2'
        }];
        loggingResource.Technical.query(function(data) {
          that.logs = data;
        });
        //that.logs = loggingResource.Technical.query();
      }
    })(angular.module('loggingModule').controller);
    

    Since the api resource was not working, I have used my github repo api link there

    The updated working plunkr is available here: https://plnkr.co/edit/cederzcAGCPVzc5xTeac?p=preview