Show session in HTML using ng-click after reloading the page

I am currently using the express-session package to store product prices in my application. Everything seems to be functioning correctly, however I am encountering an issue when trying to display the session data in HTML. For example, if there are 2 products stored in the session and I add another one, the badge should display 3. But when I refresh the page, the badge disappears and the next product added will show 4. Additionally, attempting to display the session data like {{ session.cart.totalQty }} is not working as expected. In this setup, main serves as the controllerAs, cart is a function responsible for adding products and calculating total price, while User.addToCart(...) is a service function that returns $http. My question is, how can I display the session totalQty even after refreshing the page?

Here is the HTML code:

<sapn class="badge">{{totalQty}}</span>
<a data-target="#" ng-click="main.addCart(price)" class="btn btn-success btn-block">Add to cart</a>

This is the controller logic:

app.addCart = function(product){
    User.addToCart($routeParams.id).then(function(data){ 
        $scope.totalQty = data.data.cart.totalQty;
    });
}

And finally, here is the API endpoint:

router.get('/add-to-cart/:id', function(req, res){
    var cart = new Cart(req.session.cart ? req.session.cart : {});
    Product.findById({ _id : req.params.id }, function(err, product){ 
        if(err) throw err
        if(!product){
            res.json({success:false, message: 'err'});
        } else {

            cart.add(product, product.id);
            req.session.cart = cart;
            res.json({ success:true, product: product, cart:cart });

        }
    })  

});

Answer №1

To keep track of badge count, consider using the localStorage feature to store it locally before fetching it from the server.

Here's an example:

User.addToCart($routeParams.id).then(function(data){ 
    $scope.totalQty = data.data.cart.totalQty;
    localStorage.totalQty = $scope.totalQty;
});

Then, when you load your controller, simply retrieve the stored value like this:

$scope.totalQty = localStorage.totalQty || 0;

I recommend checking out the angular-local-storage module for a more streamlined way to handle localStorage in Angular.

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

Issue: Compilation unsuccessful due to an error in the Babel loader module (./node_modules/babel-loader/lib/index.js). Syntax error

I'm currently exploring how to integrate the Google Maps Javascript API into my VueJs project without relying on the vue2-google-maps package (as it seems too restrictive to me). Here's what I've done so far, after registering my Vue compon ...

What is the best way to implement a switch that can simultaneously display both the on and off positions?

I need help customizing a toggle switch element in CSS. I want the first row to display as on (blue color) and the second and third rows to be displayed as off or grey. So far, my attempts to modify the CSS code have been unsuccessful. .switch { posi ...

Transform seconds into an ISO 8601 duration using JavaScript

Dealing with ISO 8601 durations can be quite tricky. Efficiently converting seconds to durations is my current challenge, especially in JavaScript. Stay tuned for my solution and the Jest test script coming up next. ...

Is it no longer possible to use v-for to iterate over translations in Nuxt 3 and @nuxtjs/i18n?

Imagine having an Array stored in our translations file en.js section: { title: 'This value is a string and it works perfectly', highlighted: [ { title: 'Highlighted title 1', text: 'Highlighted text ...

"Create a React button component that, when clicked, navig

I'm currently developing a web application using React and bootstrap. I'm facing difficulties in redirecting the page to another one when applying onClick to buttons. After adding a href, I'm unable to navigate to another page. Do you think ...

What is the best way to showcase the array data of two description values in a Vue v-for loop?

An array called ledgerDetails contains 32 data elements. These details are displayed in a vue v-for loop. However, within the loop, I need to show specific details from invoiceDescriptions (23 data elements) and paymentDescriptions (1 ...

Tips for sending JSON data to .js files

I am experiencing an issue here. In locations.php, I have the following code to generate JSON data: <?php $locations = array( array('2479 Murphy Court', "Minneapolis, MN 55402", "$36,000", 48.87, 2.29, "property-detail.html", ...

What could be causing transition to not be recognized as an element in HTML?

<template> <header> <nav class="container"> <div class="branding"> <router-link class="header" :to="{name : 'Home'}">>FireBlogs</router-link> </div& ...

Vuetify Autocomplete that allows for adding values not in the predefined list

I am utilizing a vuetify autocomplete component to showcase a list of names for users to select from. In the case where a user enters a name not on the list, I want to ensure that value is still accepted. Check out my code snippet below: <v-autocomplete ...

Trouble with toggling div visibility using jQuery and AJAX

I'm trying to display a specific div based on the result of an SQL query. The problem I'm facing is that I can't seem to toggle the divs asynchronously. Currently, the page needs to be reloaded for the div to reflect the changes. <?ph ...

What are some creative ways to represent data using different numerical intervals?

Looking to develop a visualization of a .CSV file containing 1.2 million lines, showcasing addresses in the format: source , destination 12.251.512 , 12.623.743 51.734.312 , 23.233.991 6334.6231.123 , 42.532.54453 (utiliz ...

Updating an element within a nested array in MongoDB using Mongoose

Currently in the process of developing a REST-API using node.js express and facing challenges with updating or adding elements to the scores Array. Here is an example document from my MongoDB collection (desired structure): Below is my mongoose model: c ...

The issue arises when attempting to render an SVG with JavaScript embedded inside using the img, object, or

Issue with the title ... please follow these steps: (view codes below) Create an svg + open it separately (name it keysaway.svg) Create html + open it individually When you observe, the svg displays a simple up and down animation but fails to work when l ...

Error message displayed as the default in ng-messages

Can ng-messages + ng-message be used to display a default error message? For example: <form name="myForm"> <input type="number" name="number" min="10" max="100" required ng-model="number" /> </form> <div ng-messages="myForm.number. ...

How are the script name and script file connected in WordPress enqueuing?

When adding a jQuery script to the function.php file using the enqueue method, how does the script name relate to the actual file that contains the jQuery code? Is the script name arbitrary, or is it derived from either the file name or the actual script w ...

Getting started with TinyMCE in Nuxt: A step-by-step guide

I need to incorporate this script into my Nuxt code: <script> tinymce.init({ selector: "#mytextarea", plugins: "emoticons", toolbar: "emoticons", toolbar_location: "bottom", menubar: false ...

Implementing Ajax functionality in MVC 3 to return a partial view

I wanted to express my gratitude for this invaluable site that has taught me so much. Currently, I am working on an MVC3 component where I need to populate a selectlist and upon user selection, load a partial view with the relevant data displayed. Everythi ...

What is the process for establishing a dependency on two distinct JavaScript files, similar to the depends-on feature found in TestNG?

I am faced with a scenario where I have two separate JS files containing test methods, namely File1 and File2. The requirement is that File2.js should only be executed if File1.js has successfully completed its execution. My current setup involves using ...

Entwine words around an immovable partition

Is it possible to create an HTML element that remains fixed in place even as the content on the webpage changes, with everything else adjusting around it? I am looking to add a continuous line that spans across a dynamic webpage. No matter how much conten ...

Support for h264 in Windows Media Player across various versions of Windows operating system

Are there specific versions of Windows that are capable of playing h264 videos with Windows Media Player installed by default? Is it feasible to determine this support using Javascript? We currently deliver MPEG-4 video files through Flash, but some users ...