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

Warning on React component listing due to key issue originating from the parent component

Alert: It is essential that each child in a list has a distinct "key" prop. Please review the render method of ForwardRef(ListItem). A child from RecipientsList was passed. I have located this issue using the react-components debugger tool on Chrome. I ad ...

Error: null does not have the property 'renderView' to be read

My goal is to set up a main page in React.js with two buttons: Option 1 and Option 2. Clicking on Option 1 should redirect the user to the Main1 page, while clicking on Option 2 should lead them to Main2. It seems straightforward, but I am encountering the ...

Learn how to collapse a collapsible section in Jquery Mobile by clicking on a link. Check out the example on JSFiddle

Is there a way to make the data-role collapsible collapse when clicking a tab link? I've tried using an on-click function without success. Any ideas or alternative solutions? Thanks. Check out my JSFiddle, where you can see that the tabs change but t ...

The success callback in JQuery Ajax does not function properly when constructing an array of Ajax calls

I am facing a challenge in building an array of custom objects by resolving promises from an array created based on another array. Consider having an array of letters = ['a', 'b', 'c']. I then map this array to make Ajax call ...

Exploring the power of JavaScript template literals within the Document Object Model

I am curious as to why this particular template literal is not functioning correctly when I try to implement it using JavaScript DOM for styling CSS. Any assistance in helping me understand this issue would be greatly appreciated! let weatherColors = [& ...

Using React - How to access prop values within child menus of Ant Design Dropdown

I have a feed of posts similar to a Facebook timeline, where each post has a dropdown menu with options for "edit, delete, report". Using the Ant Design UI library, I encountered an issue where I couldn't access the prop value "DeleteId" within the c ...

Challenge encountered when attempting to remove elements from an array within a for loop

There seems to be an issue with deleting elements from an array within a for loop. var div = document.querySelector('div'); var array = [ "iPad", "iPod", "iPhone" ]; for (let i = 0; i < array.length; i++) { let p = document.createElement ...

I'm looking for a way to use AngularJS to automatically populate options in a second select list based on the value selected in the first select list

My current HTML and javascript code is used to fill a select box dynamically using AngularJS: <select data-ng-model="selectedTestAccount" data-ng-options="item.Id as item.Name for item in testAccounts"> <option value="">Select Account ...

Pressing the shortcut key will activate the function specified in ng-click,

I have been searching for a solution to my problem, but I haven't found anything that really helps. What I am looking for is a shortcut within an ng-click directive where there is only an if condition without an else expression. Essentially, I just wa ...

Tips for identifying when input fields have been altered within an AngularJS application

On my new page, users can input data without using a form. For example: <input type='text' ng-model='ExpReport.ReportName' /> <input type='text' ng-model='ExpReport.startdate' /> There is an exit button ...

I'm struggling to figure out how to specify the data type for storing an array of objects in a variable using React.useState

I am currently working on extracting values from an .xlsx file using the SheetJS library. Below, I will provide the code snippets, errors encountered, and the different approaches I have attempted. Data extracted from var dataToJson: (6) [{…}, {…}, { ...

Steps for Verifying the Legitimacy of an AJAX Request

In the process of creating a website where users are required to solve puzzles quickly, I am utilizing JavaScript to track the time taken for each puzzle. However, I am concerned about the possibility of users manipulating this data before it is sent to th ...

Creating packing features specifically designed for resolution within a reusable module

I've decided to revamp my Angular application based on John Papa's style guide (well, mostly) and my main focus is on improving modularity. The stumbling block I've encountered is with route resolves. So far, I've been using a global ap ...

Exploring Material UI: Customizing the styling of components within TablePagination

Is it possible to customize the styling of buttons within the actions panel of the TablePagination component? import { withStyles } from '@material-ui/core'; import MuiTablePagination from '@material-ui/core/TablePagination'; const st ...

AngularJS: Enhancing User Experience by Preserving View State and Setup through Routes

Is it possible in a single page application to switch back and forth between AngularJS routes while maintaining the same state? Traditionally, this would involve binding data in a parent scope. However, for views with extensive graphical elements, this me ...

Using webpack to bundle node_modules into your application

I am facing an issue while trying to load some modules like: moment echarts In my package.json file, I have the following versions specified: "echarts": "^3.1.10" "moment": "^2.14.1" However, I am encountering the errors below: VM2282:1 Uncaught Ref ...

Displaying a div when hovering over it, and keeping it visible until clicked

I want to display a div when hovering over a button. The shown div should be clickable and persistent even if I move the cursor from the button into the shown div. However, it should be hidden when moving out of the entire area. I'm unsure about how ...

I am seeking to retrieve data from MongoDB by utilizing the limit feature, while also sending a specific query

I'm currently facing some confusion with the limit functionality in MongoDB. I want my code to specifically retrieve data for just two hotels by sending a query request from the backend. export const getHotels = async (req, res, next) => { try ...

Avoiding duplication of prints in EJS template files

In my EJS code, I have created a loop to fetch the total amount of items from the database. Here is my current code: <h2>Summary</h2> <% if(typeof items.cart!=="undefined"){ var amount = 0; %> <% i ...

What is the process of triggering an action from within getInitialProps?

I've been struggling to integrate Redux into a Next.js app, particularly when trying to use the dispatch function within getInitialProps. For some reason, the store keeps returning as undefined and I can't seem to pinpoint the issue. I've fo ...