Reputation: 33
I have a question, is it possible to create, open, modify and save the database in AngularJS (this database in SQLite 3)?
If yes, could you show an example? Thank you for the help and wasted time reading this post.
Upvotes: 2
Views: 4006
Reputation: 21
First of all, download ng-cordova, and put it in js folder.
In index.html
, you need to load ng-cordova. The order of js import is very important.
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
In your app.js
, create a variable called db
before all. This is useful to get access from all controllers.
Then add 'ngCordova'
at module dependencies.
In $ionicPlatform.ready()
, you must open your database. If you want, you can execute queries from here too.
var db = null;
angular.module('starter', ['ionic', 'ngCordova', 'starter.controllers', 'starter.services'])
.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
db = $cordovaSQLite.openDB({name: "mydatabase.db"});
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS tags (id integer primary key, name text)");
});
})
In your controller add $cordovaSQLite
, and now you can execute queries inside a controller.
Works inside scope functions as well.
.controller('TagsCtrl', function($scope, $cordovaSQLite) {
var query = "SELECT Count(id) AS count FROM tags";
$cordovaSQLite.execute(db, query).then(function(result) {
if (result.rows.item(0).count > 0) {
alert("database has rows");
} else {
alert("0 rows");
}
}, function(error) {
alert("error");
});
})
I don't know if this is the best way, but it works. Hope this help.
Upvotes: 1