Add ngCordova SQLite Plugin as a Service in Ionic
How to set up the ngCordova SQLite plugin as a reusable Angular service in the Ionic Framework.
To use SQLite in Ionic in an organized way, the best approach is to encapsulate database operations in an Angular service.
Installing the plugin
cordova plugin add cordova-sqlite-storage
Creating the service
angular.module('app')
.factory('DatabaseService', function($cordovaSQLite, $q) {
var db;
return {
init: function() {
db = $cordovaSQLite.openDB({ name: 'app.db', location: 'default' });
},
query: function(sql, params) {
var deferred = $q.defer();
$cordovaSQLite.execute(db, sql, params)
.then(function(result) {
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
};
});
Call DatabaseService.init() inside $ionicPlatform.ready() and use DatabaseService.query() in any controller to execute SQL queries.