0

Since adding the cordova-sqlite-storage plugin and refactoring controllers to something like the following I am seeing strange behavior on transitions between tabs.

angular.module('blah.controllers').controller('EquipmentCtrl', ['$scope', '$state', 'EquipmentService', 'UtilService', function($scope, $state, EquipmentService, UtilService) {

    document.addEventListener("deviceready", getRowsFromDb, false);

    function getRowsFromDb() {
        EquipmentService.getAllEquipment().then(function(rows) {

            $scope.equipmentList = rows;
            $scope.equipmentRows = UtilService.chunkArray($scope.equipmentList, 3);
        });
    }    
}]);

Everything works/looks great on initial page load but when I transition between tabs I don't see the data from sqlite on the page until I tap the same tab a second time.

The page will load as far as showing static data (title, other text, etc) but I won't see the data returned from sqlite until the second tap of the current tab. I am wondering if 'deviceready' is firing after the page has loaded but I am not sure how to combat that.

I tried this solution but didn't see any difference in behavior.

Has anybody else run into this and if so, what's the best plan of attack?

niczak
  • 3,897
  • 11
  • 45
  • 65

1 Answers1

1

Since deviceready runs outside of angularjs' context, you have to apply the digestion manually. This case, you can use $scope.$apply to apply scope changes from the apply callback:

$scope.$apply(function () {
    // do scope things here
});

The following example has been taken from your example and updated with this technique.

angular.module('blah.controllers', [])
  .controller('EquipmentCtrl', [
    '$scope',
    '$state',
    'EquipmentService',
    'UtilService',
    EquipmentCtrl
  ]);

function EquipmentCtrl($scope, $state, EquipmentService, UtilService) {

  document.addEventListener("deviceready", getRowsFromDb, false);

  function getRowsFromDb() {
    EquipmentService.getAllEquipment().then(function(rows) {
      $scope.$apply(function() {
        $scope.equipmentList = rows;
        $scope.equipmentRows = UtilService.chunkArray($scope.equipmentList, 3);
      });
    });
  }
}
lenilsondc
  • 9,590
  • 2
  • 25
  • 40