Tips for accessing cart values when navigating to a different view in AngularJS

Hi, I'm currently working on a project involving a shopping cart.

The project includes various categories with different products within each category.

When adding a product to the cart from one category, it displays correctly. Likewise, adding another product from the same category also works well and shows all previously added products.

However, when switching to a different category and adding a product to the cart, the previous products disappear from the cart page.

I am looking for a way to resolve this issue and maintain all products added to the cart without clearing it in the entire project. It is important to note that I am not using any service for this purpose, and I am hoping to achieve this solely within AngularJS.

Answer №1

There exist only two methods to persist data throughout all components of an Angular application during the digest cycle.

    1--$rootScope (not recommended)
    2--utilizing Angular Services

Based on your comment, I assume that when you mention "I am not using any service to maintain it and I want to maintain it in the angularjs only," you are referring to third-party or backend services. Angular provides its own array of services that you can leverage, such as cookies service, storage service, or alternatively, you could create your shipping cart service. My recommendation would be constructing a custom shopping cart service that manages all operations and data tracking. Angular services act as singleton objects for an application, ensuring data persistence. Creating services is pretty straightforward; here's an example:

app.service('myservice',['$rootScope','$http','$timeout',function($rootScope,$http,$timeout){
    //$rootscope useful if you want to broadcast events to the app
    //$http useful if you want to update based on the users selection or deletion
    //$timeout useful if you want to set time-based alerts or expirations
    var storage={};
    return{
       insert:function(item){/*logic to insert an item into storage*/},
       remove:function(id){/*logic to remove an item from storage*/},
       get:function(id){/*logic to get all items*/}
    }
}])

A CONTROLLER IMPLEMENTING THE SERVICE

app.Controller('Category1ItemsController',['myservice',function(myservice){
        $scope.items=[1,2,3,4,5,6]
        $scope.appendItem=function(item){
             myservice.insert(item);
        }
}]);

A VIEW UTILIZING THE CONTROLLER

<ul ng-controller="Category1ItemsController">
  <li ng-repeat="item in items">
     {{item}}
     <button ng-click="appendItem(item)">Add</button>
  </li>
</ul>

Something along these lines should provide you with more clarity. Which generator/template project are you currently working with?

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

communication flow in two directions between server and client

Looking for recommendations on a javascript/nodejs solution that enables bi-directional communication between server and client. The application flow involves the client sending a discovery service to the server, which responds with a challenge. The client ...

The website is experiencing crashes in IE11 whenever the developer tools are closed

I'm experiencing an issue with my website where it crashes internet explorer if the developer tools are not opened. I have checked for console.log calls as a possible cause, but that doesn't seem to be the problem here. The error is not just di ...

What could be the reason why document.getElementsByClassName does not seem to be functioning properly within

I've come across this code snippet const desc_object = document.getElementsByClassName("singlePostDesc"); console.log(desc_object[0]); This is how it appears in JSX {updateMode ? ( <> ...

The initial return value of $(document).height may be inaccurate, but is accurate upon recalculation

I am working on implementing a pop-up screen and I would like to darken the background when it opens. Below is the Javascript code: $(document).on('click', '.item', function(){ $("#popUp").css("display" , "block"); ...

Unable to send message to iframe from a different origin

I am encountering an issue with the code below while attempting to post a message and receiving a Blocked autofocusing on a <input> element in a cross-origin subframe. error. import React from 'react' const MyFiles = () => { React.us ...

Is there a solution to address this login code with multiple queries in Mongoose?

**I am currently in the process of creating a login route that can accept either a username or email. However, I encountered an issue where one field is being set to undefined when the other field is available, resulting in an error. My regex is specific ...

Chrome debug function named "Backbone" triggered

Backbone provides the capability to activate functions in other classes by utilizing Backbone.Events effectively. a.js MyApp.vent.on("some:trigger", function(){ // ... }); b.js function test(){ doSomething(); MyApp.vent.trigger("some:trig ...

Checking Whether a Value Entered in an Input Field Exists in an Array Using jQuery

Can someone help me with checking if a specific value is in my array? I want to achieve something like that, any suggestions on how to do it? if(jQuery.inArray($('#ValueInputTitle').val, variableValueInput) !== -1) { console.log("is in arr ...

Using radio buttons to toggle the visibility of a div element within a WordPress website

I am currently working on creating a WordPress page using the custom page tool in the admin interface. My goal is to have 3 radio buttons, with 2 visible and 1 hidden. The hidden button should be automatically checked to display the correct div (although ...

Finding a solution to the type issue of error handling in Route Handler with NextJS

I'm working on a route handler located at app/api/transactions/route.ts. Here's a snippet of the code: import { NextRequest, NextResponse } from "next/server"; import { AxiosError } from "axios"; import axios from "../axi ...

Universal Module Identifier

I'm trying to figure out how to add a namespace declaration to my JavaScript bundle. My typescript class is located in myclass.ts export class MyClass{ ... } I am using this class in other files as well export {MyClass} from "myclass" ... let a: M ...

How can we prevent the 'To Date' value from incrementing by one with each search in AngularJS when using Moment.js for conversion?

Implementing date range search functionality in AngularJS and utilizing moment.js. Despite setting the time zone, the 'To Date' field increments by one date each time. Below is the code snippet that I am using: function getSearchDate( ...

When utilizing ng-views within PhoneGap, receiving the origin is restricted due to the Access-Control-Allow-Origin policy

Having trouble getting ng-views to function properly in an Android phone app. When attempting to navigate to one of the views via a hyperlink, I encounter the error message: "Origin is not allowed by Access-Control-Allow-Origin" I have made attempts to m ...

Understanding JSON Arrays using jQuery

I've been attempting to display JSON objects in the console, but unfortunately, I'm facing some issues. The JSON data is obtained from a small API that I crafted using PHP. Here's a snippet of my JSON: { TotalResults: 2, Results: [ ...

angularJS equivalent of whenDOMReady

Greetings: Angular novice incoming. Behold, my code snippet residing in an angular.js territory: <div class="clearfix" ng-controller="Controller"> <h1>Active Ideas <button type="button" ng-click="search()">Fetch Ideas</bu ...

Preventing a back end process from continuing when an AJAX call is cancelled in a Node.js Express application

I have been working on a mean stack application. For the front end, I am using AngularJS with angucomple-alt for auto complete searching. Each time a character is entered, an ajax call is made, but if a previous ajax call is not complete, it is aborted. ...

Mastering the art of transforming JSON data for crafting an exquisite D3 area chart

I often find myself struggling with data manipulation before using D3 for existing models. My current challenge is figuring out the most efficient way to manipulate data in order to create a basic D3 area chart with a time-based x-axis. Initially, I have a ...

How can I utilize JavaScript to seamlessly loop through and display these three images in succession?

My current code is HTML, CSS, and JS-based. I am looking to design three of these div elements that appear and hide in a loop every 3-5 seconds. After the first run, I want the execution to repeat continuously. How can I modify my code to achieve this func ...

Guide on toggling visibility of a column in Material-ui based on a conditional statement

Can someone help me with code that allows me to hide or show the TableCell based on an if statement? I am currently working with MATERIAL-UI framework which can be found here: https://material-ui.com/ <TableBody> {Object.entries(servicesCode).map ...

Conflict arising from duplicated directive names in AngularJS

Hey there, I've got a question for the experts. How can I prevent conflicts with directive names when using external modules? Right now, I'm utilizing the angular bootstrap module, but I also downloaded another module specifically for its carouse ...