Tips for transferring the name field to a different page upon clicking

There are two pages in my project - the first one is called ItemMenuPage and the second one is called CartPage. The functionality I am trying to achieve is that when a user clicks on any item name on the ItemMenuPage, it should navigate to the CartPage, with the selected item name displayed.

MenuController

.controller('FoodCtrl', function($scope, $state, mySharedService) {
  $scope.addProductItem = function(product) {
    var itemName = product.itemName;
    mySharedService.setData(product);
    $state.go('app.produce');
   }
});

CartController

.controller('ProduceSaveController', ['$scope','mySharedService',
function(scope, mySharedService){
 scope.$on('handleBroadcast', function() {
   scope.itemName = mySharedService.itemName;
 })

service.js

.factory('mySharedService', function($rootScope) {
var sharedService={};
sharedService.itemName='';

sharedService.setData = function(product) {
  this.itemName = product;
  this.broadcastItem();
};
sharedService.broadcastItem = function() {
  $rootScope.$broadcast('handleBroadcast');
 };
 return sharedService;
})

Answer №1

Typically, the storage location for your shopping cart can vary. It could be in a database, session storage, or anywhere else really. The important thing is to ensure that the way you access and work with this data is correct.

angular.module('app')
.factory('cart', function()
{
    return {
        addItem: function(item){
            // Implement code here to save the item
        },
        getItems: function(){
            // Implement code to retrieve items - if using ajax, it might return a promise object
        }
     };
});

When a user is on the item page, they would use the addItem function. On the shopping cart page, they would use the getItems function.

angular.module('app')
.controller('cartController', function($scope, cart){
    cart.getItems().then(function(items){
        $scope.items = items;
    };
});

Without more specific details, this is the extent of assistance that I can provide at the moment.

Answer №2

Effective methods for establishing communication channels between different modules within your application using fundamental AngularJS features include:

  • Utilizing services
  • Leveraging events
  • Assigning models on $rootScope
  • Establishing direct communication between controllers through $parent, $$childHead, $$nextSibling, and similar means
  • Implementing direct communication between controllers using ControllerAs or other inheritance techniques

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

Hide the div when hovering occurs

I need a way to hide the 'sample' div when hovering over it and then show it again when the mouse moves away $('.secmenu').hover(function() { $('.sample').css('opacity', '0'); if ($('.secmenu&a ...

"Resetting select fields in a Django application using jQuery: A step-by-step guide

Recently, I was tasked with taking over a partially-developed Django application. Python is familiar territory for me, but I am completely new to JavaScript. This application heavily relies on jQuery for various form manipulations. One specific issue I enc ...

My stored variable in the php session is not being recalled properly

Currently, my PHP script is generating new files based on user input. I want all documents to be created using the initial input to ensure consistency. In the first PHP script, I set the variable as follows: session_start(); $_SESSION["FirstName"] = $_POS ...

Is there a distinction between the node commands 'cordova ionic' and 'ionic'? Which command should be utilized?

When it comes to node commands, is there a distinction between running npm install -g cordova ionic versus just npm install -g ionic? Which of these commands should be used for building an Ionic project? It seems that the documentation provided by Ionic F ...

Send out data every 250 milliseconds in a way that resembles debounceTime(), but without any waiting period

When the window is resized, I have a complex operation that rearranges multiple DOM elements. To prevent frequent updates, I implemented debounceTime(250ms) to introduce a delay before refreshing the components. However, this approach can cause issues if ...

How to efficiently store and manage a many-to-many relationship in PostgreSQL with TypeORM

I have a products entity defined as follows: @Entity('products') export class productsEntity extends BaseEntity{ @PrimaryGeneratedColumn() id: number; //..columns @ManyToMany( type => Categories, categoryEntity => cat ...

Utilizing JavaScript to Parse RSS XML Feeds Across Domains

Looking to parse an RSS (XML) file without relying on the Google RSS feed. I have attempted using JSONP, but it resulted in downloading the file and throwing an error "Uncaught SyntaxError: Unexpected token < ". $.ajax({ type: "GET", ur ...

Click and keystroke fusion

Greetings everyone, I've been attempting to integrate both click and keypress functionalities into my function, but unfortunately, nothing I've attempted so far has yielded any success. Here's the code snippet: function victoryMessage() { ...

The Wordpress admin-ajax.php script is failing to process the function and returning a "0" error code

I have been experimenting with processing AJAX requests in Wordpress and I'm following a particular tutorial to achieve this. The goal is to create a basic AJAX request that will display the post ID on the page when a link is clicked. The Approach ...

Events triggered by JQueryUI's .selectable functionality

I am facing a minor issue with the JQuery .selectable function. My goal is to bind events to each tab. I have successfully handled the click event for each tab, but I'm struggling when it comes to selecting two or more tabs. For instance, if I clic ...

What are all the different methods I can use to transfer element A to element B, and what are those methods?

While experimenting with Jquery, I encountered a roadblock and now have this question in mind. I wish to enclose all the anchor elements within a newly created div element. <td class="cont-mod-none-options" valign="top" align="right"> <a hr ...

Convenient way for users to easily choose an icon from a vast selection of icons

I am currently working on a web application that allows users to create new categories. These categories are then inserted into a database using form post. Each category should have an icon associated with it, and I want users to be able to select the ico ...

Angular tutorial on splitting a JSON array

I am looking to extract a portion of a JSON array in Angular. The array looks like the one in the image below.https://i.stack.imgur.com/w0hqC.png Below is the code snippet: export class AppComponent { color: string = 'green'; public stocklis ...

What is the best way to implement a subquery using EXISTS in Knex?

I'm currently facing challenges while constructing a query using knex, specifically when it comes to incorporating the 'WHERE' clause with the condition EXISTS (SELECT * FROM caregiver_patient WHERE patient_id IN (0,1)). Below is the origin ...

Generate a fresh object with distinct identifiers

I am interested in creating a new object, utilizing unique keys consisting of comma-separated IDs. For instance, I have: const d = { "1,2,3,4,5,6,7,8,9,10": [ "created_by", "modified_on", "external_o ...

Unique Soundcloud visualization using webglonDeletegist

After going through the SoundCloud documentation, I have been trying to figure out how to create a visualizer for SoundCloud tracks. The challenge is that in order to achieve this effectively, I need access to the source waveform. I suspect that direct acc ...

What is the best way to define a custom route in react-router-dom?

My goal is to have the URL display "/login" in the address bar when I am on the login page. // App.js <Routes> {isLoggedIn ? ( <Route path="/" element={<Root onLogout={handleLogout} />}> <Route index e ...

Rxjs: accessing the most recent value emitted by an observable

As shown in the demo and indicated by the title const { combineLatest, interval, of } = rxjs; const { first, last, sample, take, withLatestFrom } = rxjs.operators; const numbers = interval(1000); const takeFourNumbers = numbers.pipe(take(4)); takeFourNu ...

Is there a way to create a div that resembles a box similar to the one shown in the

Hello, I am attempting to achieve a specific effect on my webpage. When the page loads, I would like a popup to appear at the center of the screen. To accomplish this, I have created a div element and initially set its display property to 'none'. ...

Leverage uib-typeahead for iterating over an object

I'm currently working on implementing uib-typeahead to iterate through an object, but I'm stuck on what to include in the uib-typeahead directive. This is my HTML setup: <input type="text" ng-model="selected" uib-typeahead="item for item in ...