Search code examples
listcordovaionic-frameworkpage-refreshionic-view

List refresh/reload template


I'm newbie in ionic and facing problem with: I have to load and reload my template by 1 and 1 minute, and it's ok for the first time, but when the function to take the records from the server is called again, it doesn't clean the template, just add the records again, so if I have only one record on the server, it shows me two on the first minute, three on the second minute and successively.

I have tried: cache=false, window.reload, state.reload, state.go and many others tries but nothing gives the result I need, cause I simply need that the contents of the list be replaced and not added. My code:

list = function () {
$http.post(G.URL + 'page.jsp')
    .then(function (response) {
        $scope.total = response.data.records.length;
        $scope.items = response.data.records;
        $scope.counter = 1;
    }, function (error) { $scope.items = "Nothing"; });}

$interval(function () {
$scope.counter += 1;
if ($scope.counter > 59) {
    $scope.counter = 1;
    list();
    //$ionicHistory.clearCache([$state.current.name]).then(function () { $state.reload(); });    } }, 1000);

Thanks in advance


Solution

  • One of things thats happening is that you're not seeing the update because you're not digesting the new scope. $scope.$apply() and $timeout() run a digest cycle so that the scope can refresh and show new values. $http calls take time to return to the client and if you're updating the scope with delayed values you should run a digest cycle. I have cleaned up your code as well.

    .controller('Ctrl', function($scope, G, $interval, $http, $timeout) {
      // always initialize your scope variables
      angular.extend($scope, {
        total: 0,
        items: []
      });
    
     var list = function () {
        $http.post(G.URL + 'page.jsp')
        .then(function (response) {
          angular.extend($scope, {
            total: response.data.records.length,
            items: response.data.records
          });
          $timeout(); // this is used to reload scope with new delayed variables
        }, function (err) { 
          console.error(JSON.stringify(err)); 
        });
      };
    
      // call list every 1000 milliseconds * 60 = 1 minute
      $interval(list, 1000 * 60);
    
      // call list on page load so you don't wait a minute
      list();
    });