2

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.

3
  • look here - stackoverflow.com/questions/14764707/… Commented May 7, 2014 at 12:34
  • @Fabio Did you find the solution. I have trouble with creating database. Always shows OpenDatabase undefined Commented Oct 18, 2014 at 12:57
  • @james yes, but instead of using a database, a file migrated to file json Commented Oct 19, 2014 at 20:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.