vendredi 29 juin 2018

AngularJS ng-repeat refresh with new API call

Currently working on an application where I'm doing an API call to get the data and then using ng-repeat directive to populate the table on the view.

<tr md-row ng-repeat="request in requests">
        <td md-cell></td>
        <td md-cell></td>
        <td md-cell></td>
        <td md-cell></td>
        <td md-cell></td>
        <td md-cell></td>
</tr>

And in the controller, a user makes a new request and it adds a row to the database and after the success dialog comes up, I want to make a new request to the API to get the new row that the server generated, so I want to make a new API request.

So, I contact the API and get all the requests again and want to replace the data on the table with the refreshed data from the API

Here's my js promise resolve function:

var onRequests = function(response) {
  $scope.requests = [];

      response.forEach(function() {
          //Processing here and pushing to the new array
      });
  });
};

But, on creating this new array I'm assuming that the reference to the original array, which the scopes of the ng-repeat pieces have, is lost.

So, I'm trying to get a way for it to just refresh the ng-repeat table with a new array.

Here are things I've tried:

  • New array and then $applying

  • Keeping same array reference and just removing everything and doing it again, but this seems like a hacky way and I want an elegant solution

  • Using $rootScope instead for the array, which seems to work for some reason...

This is how I did the $rootScope one, which works (but seems hacky):

 var onRequests = function(response) {
      $rootScope.requests = [];

          response.forEach(function() {
              //Processing here and pushing to the new array
          });
      });
    };

For some reason this works, and I don't know why.

If anyone could help me out, that would be awesome. I've read around on other questions similar and couldn't seem to find anything helpful or exact along what I'm trying to do, from what I've found, it hasn't worked.

EDIT: Just to be clear, I've read over about a dozen other posts that have similar wording and none were exact to what I am trying to do as I said, so before flagging as duplicate, know that a lot of the other ones didn't work as solutions.




Aucun commentaire:

Enregistrer un commentaire