Retrieving information from an openDatabase using AngularJS

Encountering an issue while trying to retrieve data from openDatabase and display it in a listview. Following advice from a thread, I added $scope.$apply(); after $scope.items = $data;, but this resulted in an error:

[$rootScope:inprog] $apply already in progress
. Below is my code snippet.

index.html


    <!doctype html>
    <html lang="en" ng-app="app">

    <head>
    </head>
    <body>    
      <ons-navigator var="navi">
        <ons-page>
          <ons-toolbar>
            <div class="center">I Spent</div>
              <div class="right" ng-controller="AddExpendController">
                  <ons-toolbar-button ng-click="">
                      <ons-icon icon="ion-plus" fixed-width="false" style="vertical-align: -4px;"></ons-icon>
                  </ons-toolbar-button>
              </div>
          </ons-toolbar>

            <ons-list ng-controller="AppController">
                <ons-list-item class="item" ng-repeat="item in items" ng-click="showDetail($index)">
                    <ons-row>
                        <ons-col width="60px">
                            <div class="item-thum"></div>
                        </ons-col>
                        <ons-col>
                            <header>
                                <span class="item-title">$ {{item.e_cost}}</span>
                                <span class="item-label">{{item.e_created}}</span>
                            </header>
                            <p class="item-desc">{{item.e_memo}}</p>
                        </ons-col>
                    </ons-row>
                </ons-list-item>
        </ons-list>
    </ons-page>
  </ons-navigator>
</body>  
</html>

index.js

(function () {
    'use strict';
    var module = angular.module('app', ['onsen']);
    var db = window.openDatabase("ispentdb", "1.0", "I Spending DB", 2000000);
    module.factory('$data', function () {
    var listItems = [];
    db.transaction(function queryDB(tx) {
            tx.executeSql('DROP TABLE IF EXISTS exptable');
            tx.executeSql("Create Table IF NOT EXISTS exptable (eid INTEGER PRIMARY KEY, e_cost text, e_memo text, e_picture text, e_created text)");
            tx.executeSql('INSERT INTO exptable (e_cost, e_memo, e_created) VALUES ("2.30","testing","2015-4-13")', []);
            tx.executeSql('INSERT INTO exptable (e_cost, e_memo, e_created) VALUES ("2.32","testing","2015-4-12")', []);
            tx.executeSql('select * from exptable order by eid DESC', [], function (tx, result) {
                console.log("Returned rows = " + result.rows.length);
                for (var i = 0; i < result.rows.length; i++) {
                    listItems.push({ e_cost: result.rows.item(i).e_cost, e_memo: result.rows.item(i).e_memo, e_created: result.rows.item(i).e_created });
                }
            });
    });
    console.log(listItems);
    return listItems;
});

module.controller('AppController', function ($scope, $data) {
    console.log($data);
    $scope.items = $data;
});
})();

The problem was resolved when using the following method:

(function () {
    'use strict';
    var module = angular.module('app', ['onsen']);

    module.controller('AppController', function ($scope) {
        var db = window.openDatabase("ispentdb", "1.0", "I Spending DB", 2000000);
        db.transaction(function (tx) {
            tx.executeSql("Create Table IF NOT EXISTS exptable (eid INTEGER PRIMARY KEY, e_cost text, e_memo text, e_picture text, e_created text)");
        }, errorDB, successDB)

        function errorDB(err) {
            alert("Error processing SQL: " + err)
        }

        function successDB() {
            db.transaction(function queryDB(tx) {
                tx.executeSql('select * from exptable order by eid DESC', [], function querySuccess(tx, result) {
                    var listItems = [];
                    console.log("Returned rows = " + result.rows.length);
                    for (var i = 0; i < result.rows.length; i++) {
                        listItems.push({ e_cost: result.rows.item(i).e_cost, e_memo: result.rows.item(i).e_memo, e_created: result.rows.item(i).e_created });
                    }
                    $scope.items = listItems;
                    $scope.$apply();
                })
            });
        }
    })
})();

Answer №1

Instead of using $scope.$apply(), you have the option to utilize $scope.$evalAsync(). This function will initiate a digest loop:

$scope.$evalAsync(function() {
  // Make data updates in this section.
});

Answer №2

After putting in some time to research, I have finally managed to come up with a solution. While it may not be perfect, it is definitely functional. Take a look at it, guys.

(function () {
'use strict';
var module = angular.module('app', ['onsen']);
var db = window.openDatabase("ispentdb", "1.0", "I Spending DB", 2000000);

module.controller('AppController', function ($scope,readData) {
    var ac = this;
    ac.refreshList = function () {
    readData.transaction().then(function (data) {
        $scope.items = data;
    })        
    };

    $scope.insexp = function () {
        var cost = parseInt(document.getElementById('cost').value);
        var memo = document.getElementById('memo').value;
        if (cost == "") {
            alert("Please insert number");
        } else {
            cost = cost.toFixed(2);
            db.transaction(function (tx) {
                tx.executeSql('INSERT INTO exptable (e_cost, e_memo, e_created) VALUES (?,?,?)', [cost, memo, gettodayDate()]);
            });
            dialog.hide();
            ac.refreshList();
            document.getElementById('cost').value = "";
            document.getElementById('memo').value = "";
        }      
    }

    $scope.dialogs = {};
    $scope.show = function (dlg) {
        if (!$scope.dialogs[dlg]) {
            ons.createDialog(dlg).then(function (dialog) {
                $scope.dialogs[dlg] = dialog;
                dialog.show();
            });
        }
        else {
            $scope.dialogs[dlg].show();
        }
    }

function gettodayDate() {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!

    var yyyy = today.getFullYear();
    if (dd < 10) {
        dd = '0' + dd
    }
    if (mm < 10) {
        mm = '0' + mm
    }
    var today = yyyy + '-' + mm + '-' + dd;

    return today;
}
    function init(){
        ac.refreshList();
    }
    init();
})
module.factory('readData', function ($q) {

    var localData = [];
    var data = [];
    var selectAllStatement = "SELECT * FROM exptable order by eid DESC";

    return {
         transaction : function () {
            var deferred = $q.defer()

            db.transaction(function (tx) {
                tx.executeSql("Create Table IF NOT EXISTS exptable (eid INTEGER PRIMARY KEY, e_cost text, e_memo text, e_picture text, e_created text)");
                tx.executeSql("SELECT * FROM exptable order by eid DESC", [], function (tx, result) {
                    var dataset = result.rows;
                    console.log(result.rows.length);
                    for (var i = 0; i < result.rows.length; i++) {
                        data[i] = dataset.item(i);
                    }
                    deferred.resolve(data)
                })
            })
            return deferred.promise
        }
    }

})
})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to change the color of my Material Icons when I move my cursor over them?

Currently, I am integrating mui icons 5.2.0 into my React application. Although the icon appears on the page, it remains unchanged in color when I try to hover over it. Check out the snippet of code that I have implemented: import EditIcon from '@mu ...

Setting up Geolocation

I have been utilizing an APM tool for my work. The tool currently requires a pop-up in order to capture the user's location. However, there is now a need to capture the user's location without the pop-up appearing. Is there a method or workaroun ...

How do I preserve data within $scope upon switching views using ng-include?

Can you please take a look at this jsFiddle? http://jsfiddle.net/mystikacid/b7hqcdfk/4/ This is the template code: <div ng-app="myApp"> <div ng-controller="dataCtrl"> <div>Data : {{data}} (Value outside views)</div> < ...

Beginner's guide to using Express: a step-by-step tutorial on making API requests from client-side JavaScript to

Currently, I am immersed in a Javascript project where I utilize the Nasa Mars Rover API and Immutable Js to creatively display images and information on my webpage. By harnessing the power of pure functions and functional programming, I maintain app state ...

I'm attempting to utilize a basic webcam capture upload feature, but it seems that the upload function is not functioning properly

UPDATE: This is the complete code that I simply copied and pasted. <!DOCTYPE HTML> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script language="JavaScript" type="text/javascrip ...

Sorting through various data inputs in one JSON file

I have a JSON file containing an array of objects: obj= [{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"t ...

The ajax success() function is failing to function properly when attempting to make a call

The button's onClick() event is not navigating anywhere. There seems to be an issue with the success() function of the ajax call. Unfortunately, I am new to this and unable to pinpoint the problem. var currentAuthor=""; var currentQuote=""; $(documen ...

Error message: The Node.js filtered LS command is missing a ")" after the argument list

I've been working on the learnyounode workshop and I'm stuck on a code issue. After running it through jslint, I received this feedback: Expected ')' to match '(' from line 6 but instead saw '{'. Oddly enough, line ...

What is the best way to iterate through an ID using jQuery?

After pulling the list of doctors in my area from the database and displaying it on my webpage, I now want to load each doctor's "About" content inside a Bootstrap modal. I added an "about" column within the same database table where the doctors' ...

In Next.js, the elements inside the div created by glider-js are not properly loaded

I'm currently working on setting up a carousel in nextjs using the data retrieved from an API and utilizing glider-js for this purpose. However, I'm facing an issue where the div created by glinder-js does not include the elements that are render ...

Ensure that at least one mandatory field is implemented with React final form

Here is a code snippet that handles field validation: export const isOneFieldValid = (val: string) => { console.log(val) return val ? undefined : true } ... const validate = (field: string) => { switch (field) { case 'email': { ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...

Can you please explain the distinction between these two methods of defining controllers?

When defining controllers, what sets apart these two approaches? angular.module('myApp', ['ui.bootstrap']); function CarouselCtrl($scope) { ... } versus this... var myAppModule = angular.module('myApp', ['ui.bootst ...

Display labels for each tick on the Kendo slider in AngularJS

When using the Kendo UI Core Slider, I noticed that the default label for ticks only appears every 5. In my sliders, the max value is dynamic and can sometimes be as low as 3 or 4. This results in the user only seeing a 0 (as the min) and a few ticks on t ...

JavaScript - Unable to unselect a button without triggering a page refresh

I have a series of buttons in a row that I can select individually. However, I only want to be able to choose one button at a time. Every time I deselect the previously selected button, it causes the page to reload when all I really want is for all the but ...

Loop through an array of objects, then store each one in MongoDB

If I receive an Array of Objects from a Facebook endpoint, how can I save each Object into my MongoDB? What is the best way to iterate over the returned Array and then store it in my mongoDB? :) The code snippet below shows how I fetch data from the Face ...

Display/Modify HTML form

Looking for advice on how to create an interactive HTML form that displays data and allows users to edit it by clicking 'Edit' before submitting changes. Any suggestions on how to implement this functionality? ...

"Redirecting to an HTML page from the POST method is not supported in the Flask backend and Vanilla JS frontend setup

Utilizing the selected dropdown value from the frontend to perform calculations on the backend, resulting in an HTML page being returned. It's worth noting that no response is needed from the POST method, such as using return jsonify. Currently, I am ...

Exploring CryptoJS in a Vue.js project

https://github.com/brix/crypto-js I successfully installed CryptoJS using npm i crypto-js. However, I am facing difficulty in integrating it into my project. When I attempt to use the following code: // Decrypt var bytes = CryptoJS.AES.decrypt(cipher ...

Tips for defining a dynamic class variable in React with Flow

I am working with a map that assigns a reference to items, specifically in this scenario it is a video. const ref = this[`video-${index}-ref`]; I am seeking guidance on how to properly type this using Flow. The number of indexes may vary. ...