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

Using JavaScript to retrieve the updated timestamp of a file

Can JavaScript be used to retrieve the modified timestamp of a file? I am populating a webpage with data from a JSON file using JavaScript, and I want to display the timestamp of that file. Is there a way to do this using only JavaScript? ...

angularJS editable input field with click-to-exit functionality

One issue I encountered involved an editable text field directive in Angular, which is structured like this: myApp.directive('editable', function () { return { restrict: 'E', scope: { model: '=&apos ...

Mastering the art of handling and extracting multiple parameters from URLs in AngularJS

Within this setup, there are 2 distinct views each controlled by their respective controllers. The functionality involves clicking a link in View1 to load View2 and read the parameters associated with it. However, despite attempts made, an alert is popping ...

Modify the href attribute of an anchor tag that does not have a specified class or

I am currently using an event plugin that automatically links all schedule text to the main event page through anchor tags, like this: <td><a href="http://apavtcongresso.staging.wpengine.com/event/congresso-apavt-2018/">Chegada dos primeiros c ...

The jQuery template fails to render any content on the page

Recently, I've been exploring jQuery Javascript Templates and trying to follow a tutorial that involves fetching tweets from Twitter. The tutorial can be found here: . After carefully implementing the code as instructed, you can view my progress on t ...

Combination of AngularJS and jQuery

I have a page in which additional input fields are dynamically added based on the selection made in a drop-down menu. This page is powered by angularjs, but I had to use jQuery specifically for adding these extra input fields. Here is the HTML code snippe ...

Customize the text color of the active tab in Material-UI Tabs

I am facing a situation where I have this specific object: const tabStyle = { default_tab:{ color: '#68C222', width: '33.3%', backgroundColor: '#FFFFFF', fontSize: 15 }, active_tab: ...

Nuxt.js implemented with Auth using jwt refresh tokens

I've implemented the Auth library in my Vue/Nuxt project and have successfully set up JWT Authentication. However, I'm encountering an issue with the refresh token. The refreshToken cookie is consistently being set to null: Furthermore, when at ...

Encountering TOO_MANY_REDIRECTS issue while attempting to iFrame a Kibana dashboard with cookies

I'm currently working on integrating password-protected Kibana dashboards into an iFrame within my Node-powered Express application, as discussed in this forum thread. The Kibana setup involves X-Pack for protection and mandates user login to access v ...

Tips for uploading an input file using ajax method instead of a form

I have a dynamic table that sends all input text to my database using ajax. Here is the code I have implemented so far: <script language="javascript" type="text/javascript"> var i = 2; // This variable always points to the last row function test( ...

Uh oh! An error occurred when trying to submit the form, indicating that "quotesCollection is not defined" in Mongodb Atlas

Displayed below is my server.js file code, along with the error message displayed in the browser post clicking the Submit button. const express = require('express'); const bodyParser = require('body-parser'); const MongoClient = require ...

Tips for streamlining code using switch statements in vue.js

Is there a more efficient way to simplify this switch statement for handling 5 different cases? Can I streamline the process of updating the completion status based on each step? data() { return { stepOneIsCompleted: false, ...

Struggling to retrieve the data from a RESTful API?

I'm currently learning how to fetch an API in javascript and I'm encountering some difficulties in extracting specific parts of the response body. My goal is to store the setup and punchline of a joke in variables for later use. Here is the code ...

"Attempting to send JSON data through Express resulted in an error due to

I have encountered an issue while trying to send JSON data to a node server using Express. Despite the fact that the JSON object is valid, the server keeps throwing an error stating 'unexpected token i'. Client Side Code: $.ajax({ contentTy ...

Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users. My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates. I have attempted to push and convert the values u ...

Stop video and audio playback in an android webview

Is there a way to pause audio and video in an Android WebView without disrupting the page rendering? I have tried various methods but haven't found one that successfully pauses both the sound and the video without affecting the WebView. webView.onPau ...

The search box implemented in the navbar of AngularJS retrieves data to display in a table

Hey there! I'm trying to filter a table of data using a navbar search box located outside the view where the table is displayed. Struggling to figure out how to make this work. Here's the code snippet for the search box inside the navbar: <di ...

Having issues with the Carousel feature in Bootstrap 5.3.1 while using Angular version 15

I'm currently in the process of setting up a carousel on my homepage. It seems like everything is in place, but there's something missing. The initial image, text, and arrows all display properly, but they are non-functional. I have correctly imp ...

Implement an AJAX link on the webpage using Yii framework

I'm currently working on developing a user interface for an application, and I've encountered an issue with my code that involves adding AJAX links using a Yii helper function. echo CHtml::ajaxLink('Link', array('getajaxlinks&apos ...

When attempting to insert the "$binary" key into MongoDB using Node.js, an error occurs stating that the key must not begin with a "$" symbol

When utilizing the node driver to insert records into mongo, I encountered an issue with a certain field in my collection: { "$binary": "base64 encoded binary" }. If I directly input a key beginning with $, it triggers an error: Error: key $binary must no ...