Utilizing data from PouchDB to assign a value to a $scope variable in AngularJS

I am currently working with an AngularJS factory that retrieves data from a PouchDB database.

angular.module('app.factories', [])
.factory('ProgressDBFactory', function () {
    var factory = {};
    var pouchDb = new PouchDB('ProgressDB');

    factory.getAllData = function() {
        var dbOptions = {};
        dbOptions.include_docs = true;

        return pouchDb.allDocs(dbOptions).then(function(res) {
            return res.rows;
        });
    };

    return factory;
})

In order to populate the $scope.progressData in my controller with the data from the PouchDB, I have implemented the following code in my controller:

.controller('ProgressController', function($scope, ProgressDBFactory) {

    $scope.progressData = {};

    var progPromise = ProgressDBFactory.getAllProgressData();

    progPromise.then(function(res) {
        $scope.progressData = res;
        console.log($scope.progressData); // POINT A <= Here it prints all the results from the database.
    });

    console.log($scope.progressData); // POINT B <= here it just prints an empty object

})

When testing the above code, I noticed that at POINT A it correctly prints the result from the database. However, at POINT B it prints an empty object. Additionally, POINT B gets printed in the console before POINT A, indicating that the promise may not have finished executing by the time POINT B is executed. As a newcomer to JavaScript, I find this behavior confusing. Can someone provide clarification and suggest a solution? Your help would be greatly appreciated.

Answer №1

Point A will be executed after Point B due to the asynchronous nature of the callback function wrapping it inside a promise call to the database. Your code is correct in terms of execution order, but you may need to include a $apply within your scope assignment since it is being called outside of the Angular context (presumably from a third-party library).

progPromise.then(function(res) {
    $scope.$apply(function() {
       $scope.progressData = res;
       console.log($scope.progressData); // POINT B <= This logs all the results retrieved from the database.
    })
});

For more information on $apply, refer to: AngularJS Docs

Answer №2

(function(app){
progPromise.then(function(result) {
        app.progressInfo = result;
        console.log(app.progressInfo); // CHECKPOINT A <= Output of database results here.
    });
console.log($app.progressInfo);
    
})(tiger);

Keeping fingers crossed.

Answer №3

(function(scp){
progPromise.then(function(data) {
        scp.progressInfo = data;
        console.log(scp.progressInfo); // POINT A <= This line displays all results fetched from the database.
    });
console.log($scope.progressInfo);
    
})($scope);

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

Which programming language is more suitable for developing a chat website - PHP or JSP?

My goal is to create a web-based chat application similar to Yahoo's, utilizing JSP/PHP with AJAX. I'm debating between using JSP or PHP for this project and looking for the advantages and disadvantages of each. Which do you think would be bette ...

Retrieve the attribute values of an element in Angular after utilizing a template

As a newcomer to Angular, I am exploring the use of custom directives for the first time. Currently, I have a table where each cell contains a data attribute such as "data-dept="service". Before applying a directive to overwrite this value, I would like to ...

What is a way to adjust the width of fixed columns in a Bootstrap 4.0 responsive table?

I've been struggling to make this work despite following similar questions and answers. I attempted to adjust the column width by directly setting each one, but nothing seems to change! <thead style="white-space: nowrap"> ...

vertical lines alongside the y-axis in a d3 bar graph

https://jsfiddle.net/betasquirrel/pnyn7vzj/1/ showcases the method for adding horizontal lines along the y axis in this plunkr. I attempted to implement the following CSS code: .axis path, .axis line { fill: none; stroke: #000; } I am lo ...

Execute functions in a random order

My array contains a series of functions and is structured as shown below: var all_questions = [ show_question(1, 1), show_question(2, 1), show_question(3, 1), ]; I'm interested in executing those functions within the array in a random or ...

By default, the D3 hierarchy will collapse to the first level

I've been working on code to create an indented tree structure. My goal is to initially collapse the tree and show only the first level children or the root node. I tried a few different approaches, but none were successful. The current portion I have ...

Encountering challenges with the migration of JHipster from version 2.2x to 3.4 due to changes in the structure

Last winter, I embarked on a project with JHipster and recently updated it to the latest version (3.4). Despite following the documentation's guidelines, I noticed that the JS controllers generated by JHipster differ from the ones previously created. ...

No response data being displayed after Angular post request

After sending a POST request via Postman, I received the expected response with a status of 400. However, when I tried sending the same request using Angular's http.post in the browser, I only received a 400 error without any response data. https://i ...

Begin a new countdown timer upon clicking the next button

Currently, I am developing a bid auction website and I have implemented a countdown timer script. The timer works perfectly on the initial window load. However, when I click on the restart button, it fails to reset the countdown timer to a new value. < ...

Revising the input value by updating the properties

After clicking on the Reset link, I encounter an issue where the input value fails to update properly. class DiscountEditor extends Component { render() { <div className="inline field"> <a className="ui reset" onClick={thi ...

The malfunction of the selenium emulation feature in the node environment

Issue I am trying to implement mobile emulation in Chrome using Selenium with Express. However, despite setting the capabilities for mobile emulation with an Apple iPhone 6 device, Chrome does not open in emulation mode and no errors are displayed. c ...

The vacant array suddenly fills up with content once it is accessed

I encountered a strange scenario where the console.log indicated that the array was empty. However, upon inspection, I found 2 elements within it. This unexpected behavior prevented the component from rendering as it believed that conversations was empty. ...

`WebAuthn API allows for easy identification of fingerprints``

Google introduced WebAuthn https://developers.google.com/web/updates/2018/05/webauthn two years back. Is it possible to accurately identify the finger that a user registered or verified? For instance, the server could not only obtain the public key but a ...

Assigning a variable following a triumphant ajax request

When working with Java, you have the ability to reference an outer class by mentioning its name followed by this keyword. class A { void A() { } class B { void B() { A.this.A(); } } } Now, I'm trying to a ...

Steps to ensure a dropdown menu remains expanded when its nested menu is selected

Check out this dropdown list here, but the issue arises when clicking on a nested menu item such as "Books Registration". Once that page loads, the dropdown menu collapses like shown here. Here's a snippet of the dropdown code: <ul class="nav nav- ...

Properly handling curves in THREE.JS to ensure efficient disposal

I am facing a challenge with managing memory in my project. I have a dynamic sphere with moving points on it, and I am creating curves to connect these points. Here is an illustration of the process: https://i.sstatic.net/PGWuU.jpg As the points are cons ...

Route users away from login view when they are already logged in using Angular UI-Router

Currently, I am tackling a project that involves Angular and Meteor while utilizing the ui-router. One issue that has arisen is that when users are logged in and manually visit the /login route, my goal is to automatically redirect them to the home page. ...

Harmonize useState with the DOM

I'm encountering an issue with updating my trips array using the search input. Each time I try to update it, I seem to be getting the previous state. For example, if I search for "a", nothing changes, but when I then search for "ab", I see trips filte ...

How can we leverage Shared and Core modules alongside Feature modules in Angular development?

When developing my Angular application, I have adopted a specific architecture approach and included a shared.module.ts file in the shared folder. While leveraging lazy-loading in my app, I find myself puzzled about the necessary imports, declarations, and ...

Switching the default z-index for child elements within an HTML container

According to the specification, elements are typically drawn "in tree order" for in-flow, non-positioned elements of similar block level or float status and identical z-index. This means that elements declared last in the HTML markup appear on top. But wha ...