0

Really scratching my head over this one.

I have a controller in AngularJS with a function that runs once, then once every 5 minutes. The function gets an object from API and sets it to $scope.accounts. I need to print each key as a row in an html table.

ng-repeat in my table isn't printing any table rows the first time the function is run, but correctly prints the rows when the function is run 5 minutes later, and each time after that.

Why would it not work the first time, but only after it runs 5 minutes later?

Here is my code:

//portfolioController.js

app.controller('portfolioCtrl', function($scope, $http, portfolioFactory) {

  var getBalances = function() {
    var promise = new Promise(function(resolve, reject) {
      portfolioFactory.getBalances()
        .then((object) => {
          $scope.accounts = object;
          console.log($scope.accounts, 'scope.accounts'); //logging object immediately when page loads
          resolve();

        });
    });
    return promise;
  }

  //update all
  var getAll = function() {

    var date = new Date();
    var hours = date.getHours();
    var minutes = date.getMinutes();

    minutes < 10 ? minutes = '0' + minutes : minutes = minutes;
    console.log('--- executing update ' + hours + ':' + minutes + ' ---');

    getBalances()
      .then(() => $scope.$apply);
  }


  getAll();
  setInterval(function() {
    getAll();
  }, 300000);

});
<table>
  <tr ng-repeat="(key, value) in accounts">
    <td>{{key}}</td>
  </tr>
</table>
chuckieDub
  • 1,767
  • 9
  • 27
  • 46
  • 1
    Try calling `$scope.$apply()` as a function - right now it's not doing anything. – mhodges Jun 12 '17 at 21:33
  • Use apply in correct way. OR use $interval, that actually does interval + apply. – Petr Averyanov Jun 12 '17 at 22:04
  • The is no need to manufacture a promise with `Promise(resolve,eject)` as `portfolioFactory.getBalances().then` already returns a promise. As written it breaks the chain in the case of errors. – georgeawg Jun 12 '17 at 23:10
  • The raw `setInterval` function is not integrated with the AngularJS framework. Use the [$interval service](https://docs.angularjs.org/api/ng/service/$interval) instead. – georgeawg Jun 12 '17 at 23:12

0 Answers0