Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't update view, data-binding doesn't work - Angularjs and PhoneGap

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?

like image 290
axvo Avatar asked Apr 18 '13 16:04

axvo


1 Answers

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
}
like image 98
Bertrand Avatar answered Oct 19 '22 11:10

Bertrand