The Controller in Angular.js is initialized after the view is loaded

I am facing an issue where I need to return the URL of each ID I receive, but the URL is being generated asynchronously. This delay in generation is causing a problem as I am unable to display it on the view immediately. How can I make the code wait until the data is fetched from PouchDB and the URL is generated?

controller

$scope.getColour = function(id) {
        var texture_array = [];
        texture_array = photoList.data.economy.concat(photoList.data.luxury, photoList.data.premium);
        var db = PouchDB('new_test4');
        var obj = {};
        var array = [];
        var i;
        
        for (i = 0; i < texture_array.length; i++) {
            
            if (texture_array[i].image_url == id) {
                db.getAttachment(id, id, function(err, blob_buffer) {
                    if (err) {
                        return console.log(err);
                    } else {
                        var url = URL.createObjectURL(blob_buffer);
                        console.log(url);
                        return url;
                    }
                });
            }

        }

    };

html

<div class="item" ng-repeat="photoOuterObj in remainingEconomyColour " ng-class=" $index? '' : 'active'">
    <div class="row" ng-repeat="photoInnerObj in photoOuterObj">
        <div class="premium-carousel-image">
            <a class="color-image"> <img src="{{getColour(photoInnerObj.image_url)}}" alt="Image" /></a>
            <div class="ambience-button">
            </div>
        </div>
    </div>
</div>

Answer №1

Modify the getColor function to return a promise:

$scope.getColourPromise = function(id) {
    var texture_array = [];
    texture_array = photoList.data.economy.concat(photoList.data.luxury, photoList.data.premium);
    var db = PouchDB('new_test4');
    var obj = {};
    var array = [];
    var i;
     //Create deferred object
    var defer = $q.defer();
    // console.log(texture_array.length)
    for (i = 0; i < texture_array.length; i++) {
        //var id = texture_array[i].image_url;
        if (texture_array[i].image_url == id) {
            db.getAttachment(id, id, function handler(err, blob_buffer) {
                if (err) {
                    //return console.log(err);
                    //reject on error
                    defer.reject("db ERROR "+err);
                } else {
                    var url = URL.createObjectURL(blob_buffer);
                    console.log(url);
                    //resolve with url;
                    defer.resolve(url);
                }
            });
        }
    }
    //return promise
    return defer.promise;
};

The getAttachment method processes the getHandler function asynchronously after the completion of the getColour function, making it unable to return a value but capable of resolving a defer object.

Utilize ng-init to retrieve the url and attach it to the ng-repeat iterator object:

<div class="row" ng-repeat="innerObj in photoOuterObj">
    <!-- use ng-init to do the fetch -->
    <div ng-init="innerObj.urlObj = fetchURL(innerObj)">
        <a class="color-image"> <img ng-src="{{innerObj.urlObj.url}}" alt="Image" /></a>
        <div class="ambience-button">
        </div>
    </div>
</div>

The fetching function:

$scope.fetchURL = function(itemObj) {
    var urlObj = {};
    urlObj.url = "default.jpg";
    var promise = $scope.getColourPromise(itemObj.image_url);
    promise.then(function (url) {
        urlObj.url = url;
    });
    return urlObj;
});

Initially, the fetching returns an object with the url property set to a default value. Once the promise resolves, it will be updated to the fetched value. The watcher created by the double curly bracket {{ }} expression will refresh the DOM.

Avoid incorporating asynchronous functions within an interpolation like {{ }} as they are invoked multiple times per digest cycle.

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

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

Bing Map problem: p_elSource.attachEvent is throwing an error

I am encountering a significant issue with Bing Maps. The API link I am using is: Initially, I am seeing an error in firebug that looks like this: this.CreditsFor=function(a,i,j,h) { var e=[]; if(a!="undefined"&&a!=null&&typeof m_ta ...

How about using take(1) in conjunction with an Observable<boolean>?

After going through this insightful article, I came across the following implementation of a CanActivate check to determine whether the user can navigate to the home page: canActivate(): Observable<boolean> { return this.authQuery.isLoggedIn$.pipe( ...

Issue with this.setState() not updating value despite not being related to asynchronous updates

Just a quick note, this specific question does not involve any asynchronous update problem (at least, as far as I can tell). I currently have a class component with the following code snippet (simplified for clarity on the main issue): constructor(props ...

What is the best way to pause and wait for the user's click event in testing-library React until the state is updated?

Check out this link for the issue in codesandbox The tests in src/tests/App.test.js on codesandbox fail due to timing issues with state update after a click event (line 21). Uncommenting the function with await on line 21 can resolve this issue. What is t ...

What steps should I take to correct the color selection of a button that has been pressed down

Here is the code snippet that I am currently working with: HTTP: <label class="instructions" for="hidden_x"> Insert X: </label> <button type="button" class="button" name="button_x" value="1" id="x_1" onclick="document.getElementById(' ...

Creating a layered structure in React using custom components within the Material-UI tree

As someone new to the world of React and Javascript, I am struggling to understand why my code is not behaving as expected. I am attempting to create a tree structure using custom components as branches. However, when I run the code, the child objects do n ...

The map fails to load on the HTML page

I am struggling to load a map into my HTML page from a file located in the app folder. Despite using the correct code for inserting the map, it still does not load properly. <!-- Contact section start --> <div id="contact" class="contact"> ...

I'm encountering a problem with my vuejs application

I am currently working on a new vuejs 2 app and encountered an unexpected error. ERROR in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0&bustCache!./src/components/Customers.vue Module build failed: S ...

Enhance Your Search Functionality with an Angular Pipe

I created a custom pipe that filters the search field and displays a list of items based on the search text. Currently, it only filters by companyDisplay, but I want to also filter by companyCode and companyName. JSON [{ companyDisplay: "ABC", co ...

Error Code 18: Unable to Open Database - Troubleshooting in AngularJS and Cordova

Looking to set up an SQLite database using Angular.js and Cordova without relying on Ionic? Check out the following steps for initializing your app. $(function() { new AppInitializer(); }); var AppInitializer = function() { // Determine platform - we ...

The sole focus is on the animation within the div

Is it possible to have a circle animation within a button without overlapping it? Check out my code on this fiddle. $(document).ready(function(){ $('button').on("mouseup",function(){ $('#mousemark').removeClass("c ...

Having an issue with my Django model not properly saving data when receiving a POST

Just dipping my toes into the world of ajax and Django, so please bear with me for my messy code. I'm facing an issue where my Django model is not saving the response even after receiving a POST request. I'm attempting to create a simple like/di ...

Conceal and reveal text with a simple user click

Currently, I am working on a website project that utilizes bootstrap. However, I am facing some uncertainty regarding how to effectively hide and display text: <nav class="navbar navbar-light" style="background-color: #e3f2fd;"> ...

What is the best way to manage json-parse errors in a node.js environment?

After countless hours of research, I am still unable to find a solution to my seemingly simple and common problem: In Node.js using Express, I want to retrieve JSON-data via http-POST. To simplify the process, I intend to utilize the app.use(express.json( ...

Disabling the 'fixed navigation bar' feature for mobile devices

Here's a code snippet that I'm working with. It has the ability to make the navigation stick to the top of the page when scrolled to. HTML <script> $(document).ready(function() { var nav = $("#nav"); var position = nav.position(); ...

Adjust tool tip text on the fly

As a beginner, I created a test table and now I want to make the tool tip text change dynamically when I hover over the table with my mouse. Ideally, I would like the tool tip text to correspond to the content of the table cell. Currently, I only have stat ...

Question: How come I am receiving the error message "TypeError: Cannot read property 'toLowerCase' of undefined" in React JS?

Hi there, I'm new to this and trying to create a search filter. However, I keep encountering an error that says: Error: Cannot read property 'toLowerCase' of undefined It seems like the issue is related to the data type used with toLowerCa ...

Looking to dynamically assign a value to ngModel that comes from user input in Angular version 4

Within this context, we have two distinct addresses for shipping and billing purposes, each with its own unique value. To handle this scenario, we have leveraged reusable components, specifically a select-country component. <select-country [addressType ...

Angular Select Menu Issue: Unusual Dropdown Positioning in Internet Explorer

Currently, I am gradually learning Angular and working on simple projects to test compatibility with different browsers. Right now, I have a basic script that binds a menu to a JSON string array. My goal is to transition from using JavaScript DOM manipulat ...