Selecting web data using AngularJS: A comprehensive guide

Seeking the best approach to insert and display data from a WebSQL table using ng-repeat, I am utilizing the Angular WebSQL Module by paulocaldeira17. Despite successfully inserting remote data into the local database, the $scope.localproducts array remains empty when attempting to access it. This issue arises when trying to call the insert data function.

I am struggling to return the ProductsFactory.localproducts array to my controller from the Factory's selectAllData function.

The problem occurs when clicking a button that triggers the insertData function in my Controller.

If anyone could offer guidance on improving the code below or suggest a more effective alternative, I would greatly appreciate it as I am relatively new to Angular.

.controller('DownloadProductsCtrl', ['$scope','ProductsFactory', function ($scope, ProductsFactory){
    $scope.products = ProductsFactory.products;
    $scope.localproducts = ProductsFactory.localproducts;

    $scope.insertData = function(){
        ProductsFactory.getRemoteData().then(function(results){
            $scope.localproducts = ProductsFactory.localproducts;
            console.log( $scope.localproducts); //This shows an empty array
        });
    }; }])

.factory('ProductsFactory', ['$webSql', function($webSql){
    db = $webSql.openDatabase('myappdb', '1.0', 'Test DB', 2 * 1024 * 1024);
    ProductsFactory = {};
    ProductsFactory.products = [];
    ProductsFactory.localproducts = [];

    ProductsFactory.getRemoteData = function () {
        return $http.get('./products/list.json')
        .success(function (data) {
            ProductsFactory.products = data;
            ProductsFactory.insertData(data);
        })
        .error(function () {
            console.error('Error');
        });
    };

    ProductsFactory.insertData = function (data){
        angular.forEach(data, function(value, key) {
            db.insert('products', value).then(function(results) {
                <!-- In here I like to count the total inserted items and display it on the page, but not sure how to send it to a scope in my controller -->
            });     
        });
        ProductsFactory.selectAllData();
    };

    ProductsFactory.selectAllData = function(){

        db.selectAll("products").then(function(results) {
          for(var i=0; i < results.rows.length; i++){
             ProductsFactory.localproducts.push(results.rows.item(i)); 
          }
          console.log(ProductsFactory.localproducts); //This shows an empty array
        });
    };

    return ProductsFactory;

}]);

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

Why won't my navigation bar stay in place when I scroll down on the screen?

I'm trying to create a sticky navigation bar that becomes fixed when the user scrolls down to 200 pixels, but it's not working properly. I want it to behave like in this example: import React,{useState,useEffect} from 'react' functio ...

Creating a list repeater using v-for in Vue.js 2 with computed property

Seeking assistance with adding computed columns to a table (last three columns). Suspecting the issue lies in the computed property not correctly referencing the record. Any simple solutions that I might be overlooking? Appreciate any thoughts or insights! ...

Ensure no duplicate values are pushed into array when using angularjs foreach loop

I have a specific array that I am using in my foreach function $scope.categoryList = [ { "id": 44, "creationTimestamp": "2019-11-15 17:11:17", "name": "FIXED ", " ...

Adjust the appearance of a .obj file in three.js dynamically

Currently, I am attempting to dynamically swap the image texture on a loaded .obj file in three.js. Below is the modified code extracted from the three.js examples: var container, stats; var camera, scene, renderer; var mouseX = 0 ...

Events for validation on the client side and user interface blocking

Lately, we have implemented HTML 5 client-side validation in our forms. A unique situation arose during this process. To prevent multiple form submissions and give it a sleek appearance, we added an overlay with a loading indicator when the form is being ...

What is the process of setting up a route for a logged-in user on the profile page in Next

In my current web application using Next.js and Redux, I have a profile page feature that allows users to view other users by accessing URLs like website.com/aadhit or website.com/robert. My issue arises when a logged-in user with the username "richard" a ...

Is it recommended to utilize addEventListener?

Is it better to use the addEventListener method in these scenarios? <input id="input" type="file" onchange="fun()> or document.getElementById("input").addEventListener("change", function() { fun(); }); What are the advantages of using one over ...

Leveraging Next.JS for static site generation with Apollo client-side data fetching

Utilizing Next.JS SSG has greatly enhanced the loading speed of my website. However, I am facing a challenge where I need to fetch some data client-side that is specific to the logged-in user. For example, imagine a YouTube-like website with a Video page ...

Is there a way to retrieve the value from a select tag and pass it as a parameter to a JavaScript function?

I would like to pass parameters to a JavaScript function. The function will then display telephone numbers based on the provided parameters. <select> <option value="name-kate">Kate</option> <option value="name-john">John& ...

Only display one alert for Jquery validation

Is it possible to make the alert show only once if both fields, alder and gender, are invalid when running the code below? $(function(){ $("#formTest").validate({ rules : { alder : { ...

Error: JSONP Label Validation Failed

My JSON URL is: The above URL returns the following JSON: { token: "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72" } Edit: Changed it to {"token": "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72"} ...

Engaging three-dimensional design inspired by JavaScript frameworks

I'm interested in developing an interactive 3D application using JavaScript. I'm curious to know if either babylon.js or three.js have support for interactivity. I've searched for information on this but haven't found much, and the docu ...

The issue with the NextJS Layout component is that it is failing to display the page content, with an error message indicating that objects cannot be used

I am embarking on my first project using Next JS and after watching several tutorial videos, I find the Layout component to be a perfect fit for my project! However, I am encountering an issue where the page content does not display. The Menu and Footer a ...

Give an npm package a nickname using a browserify shim

I'm in the process of transitioning from requirejs to browserify. One of the dependencies I have is for masonry. Trying to shim it using the bower version was proving to be a little challenging (more on that can be found here). Instead, I decided t ...

Dealing with adding up optional values from v-model in Vue.js can be a challenging task

Within this function, I need to display the remaining amount. remainingAmount: function() { return parseFloat(this.sumAmount) - (parseFloat(this.cash) + parseFloat(this.kNet) + parseFloat(this.kNetOnline)); } The three parameters cash ...

The weather API key seems to be malfunctioning

I'm encountering an issue with the Open Weather API where I keep receiving a network error when I send a request for data about a specific city. Below is the code snippet responsible for fetching the resource. actions/index.js import axios from "ax ...

Pattern for handling errors in an efficient and streamlined manner

Currently, I am exploring the use of Express for developing a basic JSON API. However, I have concerns about how to effectively manage input parameter validation and error handling in my project. Errors can occur during both the validation process and when ...

What could be causing my NextAuthJS discord login to function in the test environment but fail to deploy in production on NextJS 13?

After attempting to deploy my NextJS application on Vercel, I encountered a problem with the AuthJS sign-in model. While running the program using npm run dev, everything works smoothly and I can log in to my Discord account linked to the developer portal& ...

Foreign key is not being posted when submitting the form using Laravel and Vue

My dilemma involves managing two tables. Here is the structure of each: Table one, referred to as "parties", consists of the following fields: public function up() { Schema::create('parties', function (Blueprint $table) { $table-> ...

Observe a group of handpicked elements and calculate the total of their IDs

I am trying to ensure that at least one value is selected from a list of select-elements. I have created a small demonstration on http://plnkr.co/edit/bLh5Gp7fsLphjX0hcLSB?p=preview $scope.$watch('vm.list', function(a, b) { alert('changed ...