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

Utilize jQuery to enclose nested elements within a parent element

There is a Markup presented below, where this HTML content is being generated from Joomla CMS. I am seeking a jQuery method to reorganize this HTML structure without modifying its PHP code. <div class="item column-1"> <div class="page-header"& ...

Setting up a basic webhook server with Node and Express

I'm struggling to locate comprehensive tutorials on webhooks for beginners. Being new to this concept, I have only come across basic explanations of how they operate. Our current requirement is to inform users of our APIs about new records. With Kafk ...

React Higher Order Components (HOCs) are functioning correctly with certain components but not

I have encountered an issue where using a Higher Order Component (HOC) to bind an action to various types of elements, including SVG cells, results in unintended behavior. When I bind the onClick event handler normally, everything works fine, but when I ap ...

Tips on preventing the insertion of special characters into a form field with the help of jQuery

I'm implementing a feature to restrict users from using special characters in the text input field. While I have successfully prevented users from typing these characters, I am also looking to prevent the pasting of any special characters as well. FID ...

ng-tags-input not functioning as expected with autocomplete feature

When I add a tag by selecting from a list populated using an $http request, the tag is added but the text that I have typed remains with an ng-invalid-tag class. Screenshots: 1) Initially: 2) Typing 3 letters to make an HTTP call: 3) Now after selecting ...

"How to change the hover background of a select element in Chrome from its default setting to something else

Is there a way to remove the background color on hover and replace it with a different color? .drp-policydetails { border: 1px solid #dddddd; background-color: #ffffff; } <div className="form-group"> <select className="form-control drp-po ...

"Trouble with JavaScript boolean values in if-else conditions - not functioning as expected

While utilizing true/false values and checking if at least one of them is true, I am encountering an issue with the if/else statement not functioning as expected. Here is the code snippet: $scope.checkValues = function (qId) { var airport = $scope.air ...

Building module dependencies in the Dojo dojo

I'm in the process of utilizing the Dojo builder to compile a unified file that encompasses all the necessary modules for my application, excluding the application itself. Below is an illustration of a layer definition: layers: { 'dojo/dojo ...

Encountered an Error: Trying to use a function that is undefined - While utilizing Jquery Tabs

Working on implementing Jquery Tabs using the "description" and "reviews" li tags as tabs. Testing it out here . Everything seems to be functioning correctly here Key Points: This is Wordpress Multi-Site setup. The issue occurs in certain folders or "si ...

Tips for verifying the rendered view post data retrieval from an API in Vue JS

Having trouble retrieving data from the API using Vue JS and printing the page? After fetching the data, some elements may not render completely when trying to print, resulting in blank data being displayed. While using a setTimeout function may work for s ...

Encountering an Issue with NextJS on GAE: EROFS Error indicating a read-only file system

Trying to deploy a customized Next.js application into Google App Engine has hit a snag. The project runs smoothly locally and on Google Cloud Platform CLI, but upon successful deployment using gcloud app deploy, an error arises when opening the app. 2020 ...

Using Three.js: Cloning Mesh and Material to Easily Toggle Clone Opacity

By using the command Mesh.clone();, it is possible to duplicate the mesh. Upon further investigation, I discovered that both the geometry and material are preserved in the clone. However, my goal is to independently adjust the opacity of each mesh. This le ...

The margin of the parent container is influencing the margin of the child element

Purple Working on displaying a rectangle shape in a browser using divs in my React project. Everything works fine, but when I add margin to the parent base and then draw the boxes, there's some space between the mouse cursor and the actual box. The ...

Selenium Refuses to Launch My Local Browser Despite Explicit Instructions

While using Chrome browser with selenium, I encountered an issue related to browser profiles. Everything works smoothly when the correct binary path is provided, but if an incorrect path is given, it refuses to run. The specific problem arises when the br ...

"The functionality of the express post method does not seem to be working properly when accessing

I am having trouble retrieving form data sent using the "POST" method from an HTML form in my app.post method. I am unable to access anything from req.body. Can anyone point out what mistake I might be making? Here is my HTML form - <form method=" ...

Can you please explain how I can retrieve information from a Firebase collection using the NextJs API, Firebase Firestore, axios, and TypeScript?

I'm currently utilizing api routes within NextJS 13 to retrieve data from Firebase. The code for this can be found in api/locations.tsx: import { db } from "../../firebase"; import { collection, getDocs } from "firebase/firestore"; ...

Developing a user management platform using Node.js

I need a system for managing users hierarchically. There are 3 levels in the hierarchy: User Manager Admin The Admin should be able to view and edit registrations for both 'User' and 'Manager' roles. A Manager should only b ...

Problem with Google's PageSpeed Insights - Focus on Making Most Important Content Visible

During the process of creating a comprehensive website for a client who has a strong affinity towards Google tools and recommendations, I have encountered an interesting challenge: Despite my best efforts, I seem unable to attain a flawless score for the ...

Generating option list from API JSON responses

I am currently developing a news app using React. I have set up my API to fetch data from newsapi.org and my goal is to display the available news source options in a dropdown list within my select component. However, instead of listing all news sources w ...

Is it possible to pass an Array into a callback function in element-ui's el-autocomplete component?

I attempted to utilize the el-autocomplete tag in its simplest form: using an Array returned by a callback function (JSFiddle version). Vue.component('button-counter', { data: function() { return { selectdusers: [], user: &ap ...