I am currently developing a PhoneGap/Cordova application with Ionic framework, utilizing SQLite (with ngCordova) for persistent storage. The main functionality of the app revolves around a scrolling list of items fetched from the SQLite database.
listController.js
.controller('ListCtrl', [
'$scope',
'dataFactory',
function($scope, dataFactory) {
var items = dataFactory.getAllItems().then(function(data){
$scope.allItems = data;
});
}
]);
dataFactory.js
.factory('dataFactory', [function($window, $log, $q, $cordovaSQLite, dummyDataGenerator){
var db_;
// ...lots of SQLite fun in here
// cascading async callbacks to load the database and inject dummy data
var openDB_ = function(){...};
var createTable_ = function(){...};
// etc
var getAllItems = function(){
var q = $q.defer();
$cordovaSQLite.execute(db_, sqlSelectString, []).then(
function(results) {
$log.log("SQL SELECT successful");
var i, len, allItems = [];
for(i = 0, len = results.rows.length; i < len; i++) {
allItems.push(results.rows.item(i));
}
q.resolve(allItems);
},
function (err) {
q.reject(err);
}
);
return q.promise;
};
return { getAllItems: getAllItems };
]});
Initially, I faced an issue where the controller executed getAllItems()
before the data was ready, resulting in an empty view. To address this, I attempted delaying the factory return by implementing a factoryReady()
function.
var factoryReady = function(){
return {
getAllItems: getAllItems
};
};
However, this led to an undefined error as the entire factory was not available when initially called. Despite observing the SQL database being populated correctly over time, Angular threw an exception prematurely.
Realizing the predictability of this behavior, I explored solutions like using resolve
in ui-router to ensure proper readiness of asynchronous data sources. Unfortunately, these approaches did not address the core issue with internal async operations within my service.
If you are knowledgeable about AngularJS services and handling asynchronous data initialization, your insights would be greatly appreciated. Thank you.