Ionic Sqlite database using Service to get data dynamically
10:58 AM
If you want to use SQLite for your Ionic app then you can prefer http://ngcordova.com/docs/plugins/sqlite/ and If you want to access data form SQLite DB using the Service or Factory, is a good practice. Here is the sample code for access data form SQLite via factory :
Define Controller(in controller.js) :
Define Controller(in controller.js) :
controller('dataCtrl', function($scope, factoryData) {
factoryData.all().then(function(response) {
$scope.data = response;
});
})
Define Factory(in services.js) :
.factory('factoryData', function($cordovaSQLite, $timeout, $q) {
var dataFun = function(deferred) {
var data = [];
var query = "SELECT * FROM tbl"
$cordovaSQLite.execute(db, query).then(function(res) {
if (res.rows && res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++) {
data.push({
"id" : res.rows.item(i).id,
"name" : res.rows.item(i).name
});
if (i == res.rows.length - 1) {
deferred.resolve(data);//send final data to controller
}
}
} else {
deferred.resolve(data);//send final data to controller
}
}, function(err) {
console.error(err);
});
};
return {
all : function() {
var deferred = $q.defer();
dataFun(deferred);
return deferred.promise;
}
};
});
Here '$cordovaSQLite' is a pre define function in ngCordova, if you don't want to user the ngCordova then you can use 'tx.executeSql' place of '$cordovaSQLite.execute' and for more details visit https://github.com/litehelpers/Cordova-sqlite-storage
0 comments