Skip to content

Instantly share code, notes, and snippets.

@lykmapipo
Forked from botris/addsqlite.sh
Last active June 11, 2018 10:46
Show Gist options
  • Save lykmapipo/6451623a54ef9b957a5c to your computer and use it in GitHub Desktop.
Save lykmapipo/6451623a54ef9b957a5c to your computer and use it in GitHub Desktop.
cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin.git
var db = null;
angular.module('myapp', ['ionic', 'myapp.controllers', 'myapp.services', 'ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
if(window.cordova) {
// App syntax
db = $cordovaSQLite.openDB("myapp.db");
} else {
// Ionic serve syntax
db = window.openDatabase("myapp.db", "1.0", "My app", -1);
}
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS team (id integer primary key, name text)");
});
})
.controller('TeamCtrl', function($scope, Team) {
$scope.team = [];
$scope.team = null;
$scope.updateTeam = function() {
Team.all().then(function(team){
$scope.team = team;
});
}
$scope.updateTeam();
$scope.createNewTeamMember = function(member) {
Team.add(member);
$scope.updateTeam();
};
$scope.removeMember = function(member) {
Team.remove(member);
$scope.updateTeam();
};
$scope.editMember = function(origMember, editMember) {
Team.update(origMember, editMember);
$scope.updateTeam();
};
})
<!DOCTYPE html>
<html>
<head>
<!-- standard Ionic head -->
<!-- Download https://github.com/driftyco/ng-cordova/archive/master.zip -->
<script src="js/ng-cordova.min.js"></script>
angular.module('myapp.services', [])
.factory('DBA', function($cordovaSQLite, $q, $ionicPlatform) {
var self = this;
// Handle query's and potential errors
self.query = function (query, parameters) {
parameters = parameters || [];
var q = $q.defer();
$ionicPlatform.ready(function () {
$cordovaSQLite.execute(db, query, parameters)
.then(function (result) {
q.resolve(result);
}, function (error) {
console.warn('I found an error');
console.warn(error);
q.reject(error);
});
});
return q.promise;
}
// Proces a result set
self.getAll = function(result) {
var output = [];
for (var i = 0; i < result.rows.length; i++) {
output.push(result.rows.item(i));
}
return output;
}
// Proces a single result
self.getById = function(result) {
var output = null;
output = angular.copy(result.rows.item(0));
return output;
}
return self;
})
.factory('Team', function($cordovaSQLite, DBA) {
var self = this;
self.all = function() {
return DBA.query("SELECT id, name FROM team")
.then(function(result){
return DBA.getAll(result);
});
}
self.get = function(memberId) {
var parameters = [memberId];
return DBA.query("SELECT id, name FROM team WHERE id = (?)", parameters)
.then(function(result) {
return DBA.getById(result);
});
}
self.add = function(member) {
var parameters = [member.id, member.name];
return DBA.query("INSERT INTO team (id, name) VALUES (?,?)", parameters);
}
self.remove = function(member) {
var parameters = [member.id];
return DBA.query("DELETE FROM team WHERE id = (?)", parameters);
}
self.update = function(origMember, editMember) {
var parameters = [editMember.id, editMember.name, origMember.id];
return DBA.query("UPDATE team SET id = (?), name = (?) WHERE id = (?)", parameters);
}
return self;
})
@GRPS
Copy link

GRPS commented May 17, 2016

Fantastic example. Helped me so much I could kiss you! Thank you.

@rhuanbarreto
Copy link

Thanks a lot!!!! This was a huge shortcut for me!

@banxuanhoa
Copy link

does index.html file error ? i want to display a input field for input member and add it to database, but i can't do it by my self, it ran to error, please help me

@hamdiamine
Copy link

Thanks a lot

@skeletor069
Copy link

`angular.module('app.services', [])

.factory('DBA', function($cordovaSQLite, $q, $ionicPlatform) {
var self = this;

// Handle query's and potential errors
self.query = function (query, parameters) {
  parameters = parameters || [];
  var q = $q.defer();

  $ionicPlatform.ready(function () {
    $cordovaSQLite.execute(db, query, parameters)
      .then(function (result) {
        q.resolve(result);
      }, function (error) {
        console.warn('I found an error');
        console.warn(error);
        q.reject(error);
      });
  });
  return q.promise;
};

// Proces a result set
self.getAll = function(result) {
  var output = [];

  for (var i = 0; i < result.rows.length; i++) {
    output.push(result.rows.item(i));
  }
  return output;
};

// Proces a single result
self.getById = function(result) {
  var output = null;
  output = angular.copy(result.rows.item(0));
  return output;
};

return self;

})

.factory('Categories', [function($cordovaSQLite, DBA){
var self = this;

self.all = function() {
  return DBA.query("SELECT id, category_name FROM categories")
    .then(function(result){
      return DBA.getAll(result);
    });
}

self.get = function(memberId) {
  var parameters = [memberId];
  return DBA.query("SELECT id, category_name FROM categories WHERE id = (?)", parameters)
    .then(function(result) {
      return DBA.getById(result);
    });
}

self.add = function(member) {
  var parameters = [member.category_name, "blank"];
  return DBA.query("INSERT INTO categories (category_name, icon_name) VALUES (?,?)", parameters);
}

self.remove = function(member) {
  var parameters = [member.id];
  return DBA.query("DELETE FROM categories WHERE id = (?)", parameters);
}

self.update = function(origMember, editMember) {
  var parameters = [editMember.id, editMember.category_name, origMember.id];
  return DBA.query("UPDATE categories SET id = (?), category_name = (?) WHERE id = (?)", parameters);
}

return self;

}])`

I created a factory same as the Team. But whenever I call any function of this from any controller, it says that cannot read property "query" of undefined. Any suggestion on how can I get it working? Thank you.

@leocfox
Copy link

leocfox commented Aug 25, 2016

It works perfectly in the browser but when on a device or emulator nothing happens and no error. Exact same code copied and pasted to ionic project, build and run to a device or emulator. Please, can you help me figure out why this does not work on the device or emulator?

@pledges
Copy link

pledges commented Aug 30, 2016

Thanks man, this is a life saver.

@Hiralkhakhriya
Copy link

plzz give the full code if index,html file..

@JuanjoSalvador
Copy link

Great example!

@adi928
Copy link

adi928 commented Dec 3, 2016

Does one need $cordovaSQLite in the 'Team' factory?

@gitszboy
Copy link

gitszboy commented Jan 5, 2017

Hey @skeletor069 did you find a solution to your problem? Am facing the same issue.

Thanks,
Jim.

@cristianmeza
Copy link

Thank you, this has helped me a lot. Greetings from Chile

@edeortuzar
Copy link

Greate job! Thank you from Argentina

@mbudak
Copy link

mbudak commented Jun 11, 2018

this is awesome, you saved my day.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment