I am trying to make a simple todo application using PhoneGap (for Android device). I also used AngularJS for data-binding.
I want to display the list of tasks saved in database. When I debug with chrome debugger, I can see the SQL request worked but nothing displays when I launch the application on an emulator or on the device.
DbCtrl.js
var myApp = angular.module('myApp', []);
function DbCtrl($scope) {
$scope.init = function() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(populateDB, errorDB, successDB);
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, todo)');
tx.executeSql('INSERT INTO DEMO (id, todo) VALUES (1, "first todo")');
tx.executeSql('INSERT INTO DEMO (id, todo) VALUES (2, "Second todo")');
}
function errorDB(err){
alert("Error processing SQL: "+err)
}
function successDB(){
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(queryDB, errorDB);
}
// Query the database
function queryDB(tx) {
tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorDB);
}
// Query the success callback
function querySuccess(tx, results) {
console.log("Returned rows = " + results.rows.length);
$scope.todos = results.rows;
}
$scope.init();
}
DbIndex.html
<body ng-app="myApp" >
<div ng-controller="DbCtrl">
<div>
<h1>SimpleTodos</h1>
</div>
<div id="mainContent">
<ul ng-repeat="todo in todos">
<li>{{todo.id}}</li>
</ul>
</div>
<div class="ui-bar">
<a href="edit.html">Add Note</a>
</div>
</div>
<script src="../libs/cordova-2.5.0.js"></script>
<script src="../libs/angular-1.0.5.js" type="text/javascript" ></script>
<script src="dbCtrl.js" type="text/javascript" ></script>
</body>
Someone knows why the view isn't updated? Do we have any way around?
This is happening because the query is asynchronous. After updating the model you have to trigger the digest so angular can update the view.
// Query the success callback
function querySuccess(tx, results) {
console.log("Returned rows = " + results.rows.length);
$scope.todos = results.rows;
$scope.$apply(); //trigger digest
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With