Angular is capable of constructing an array

Whenever a user clicks on a tag in my app, I want to capture the id of the product clicked and store it in an array.

This is how my view looks:

<ion-view view-title='Products'>
<ion-content>
    <div class="row">
        <div class="col col-25" ng-repeat="row in products">
            <a href="#/main/tickets/{{row.productId}}" class="button button-block button-light">{{row.product}}<br/><small>{{row.price | currency}}</small></a>
        </div>
    </div>
</ion-content>

In the above code snippet, I extract the row.productId of the product. Here's how it's handled in my app.js file:

This is from my app.js:

.state('main.tickets', {
            url: '/tickets/:productId',
            views: {
                'tickets': {
                    templateUrl: 'templates/tickets.html',
                    controller:  'ticketsController'
                }
            }
        })

The productId is retrieved as a URL parameter.

Below is my controller function:

.controller('ticketsController', function($scope, $localStorage, $stateParams){

var tickets = [];

tickets.push($stateParams.productId);

console.log(tickets);

})

The tickets array successfully stores the id, but each time a new productId is clicked, the array resets because of the declaration. The goal is to retain all the productId values without resetting the array. Unfortunately, I'm unable to figure out a way to achieve this at the moment.

Answer №1

The issue you're facing is that you're using a controller to store your tickets array, leading to a new controller and scope being created every time you visit a ticket page.

An effective solution to this problem is to store the tickets array in a service, ensuring persistence across different pages.

.service('ticketModel',function() {
    var self = this;
    self.ticketArray = [];
}

.controller('ticketsController', function($scope,$statePrams,ticketModel) {
    ticketModel.ticketArray.push($stateParams.productId);
    console.log(ticketModel.ticketArray);
})

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

Personalize the req.body object in Nodejs

I'm curious to know if it's possible to customize the req.body that is sent to MongoDB. Currently, my req.body looks like this: { f_name: 'John', l_name: 'Doe', phone: '4521234892345' } However, I would like it ...

ASP not recognizing AngularJS input states

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Staffing_Tool.Login" %> <!DOCTYPE html> <html> <head runat="server"> <script src="scripts/angular.min.js" type="text/javascript"></scr ...

Strange outcome in Three.js rendering

Is it possible to correct the reflection issue around the cycles? I noticed some strange results on my object and I've attached pictures to illustrate the problem. Current result in Three.js: https://i.sstatic.net/iJbpm.jpg https://i.sstatic.net/hv ...

tips for deactivating routerLink functionality on anchor elements

Working on an Angular application that requires me to create an image slider. However, due to the presence of router links in the application, the anchor tags in the image slider keep redirecting. I want to prevent this redirection and instead successful ...

res.send() triggers an error of TypeError: Attempting to convert circular structure to JSON

I've encountered an error message that has been discussed before, but none of the proposed solutions seem to work for my situation. My current project involves building a backend express server to manage API requests for a React application. I have c ...

Tips on utilizing Ajax for updating the RenderBody() segment

Can anyone help me understand why my Ajax.ActionLink menu item is calling JavaScript twice when I try to use it for the second time? I simply want to update the RenderBody() after clicking on a menu item. _Layout.cshtml: ... <body> <div i ...

Utilizing *ngIf for Showing Elements Once Data is Completely Loaded

While working on my Angular 2 app, I encountered an issue with the pagination UI loading before the data arrives. This causes a visual glitch where the pagination components initially appear at the top of the page and then shift to the bottom once the data ...

Can you explain the purpose of the yarn command --prefer-offline?

After installing an npm package like react for the first time using yarn add react I noticed that the .yarn-cache folder contains many files. I assume this is where yarn stores the local cache, so when I install react again in the future, it will be pulle ...

Manipulating URLs in Javascript: Removing portions and appending queries

Is there a way to modify an URL by removing a portion and adding a query before returning it? For example: locahost:8080/product/orders/1. I would like to remove the orders/1 part and add /?query="sample". ...

Window backdrop being filled

I am attempting to set a background image that fills the entire window regardless of its size. I have implemented html, css and script as shown below: // Function adaptImage() // Parameters: targetimg function adaptImage(targetimg) { var wheight = $ ...

Why is my AngularJS controller receiving 'undefined' data from my service request?

Question: I am facing an issue where my service is successfully retrieving the necessary data, but my controller is not able to access it. What could be causing this problem? Service: Below is the code that my controller calls. // search.service.js (func ...

Issue encountered with AJAX request using JavaScript and Express

I'm brand new to this and have been searching online for a solution, but I can't seem to figure it out. It's possible that I'm making a basic mistake, so any assistance would be greatly appreciated. I'm trying to create a simple f ...

Error found in Node module: SQL2 - token was not expected

Attempting to establish a connection to sql2 with the following code: const mysql = require('mysql2'); var con = mysql.createConnection({ host: "localhost", user: "abc", password: "123", database: &q ...

Preventing Event Bubbling with Hammer.js 2.0: A Step-by-Step Guide

I have a situation with a parent and child div. I want to prevent panning or dragging on the child from affecting the parent. I came across a similar question that was asked a year ago, but I am using a newer version of Hammer.js with the jQuery wrapper. ...

Leveraging Lodash to retrieve values based on specific keys, even when certain keys are missing

How can I efficiently utilize Lodash while iterating through an array to extract and assign relevant values? I have an unfiltered array which contains ID and name[x].text elements. Some objects in the array may not have French text available, in which cas ...

Tips for resolving the React(TypeScript) issue "Invalid hook call."?

I received an error message stating: "Invalid hook call. Hooks can only be called inside of the body of a function component." within my React function: interface Items { items: any[] } const [items, setItems] = useState<Items>(); const ItemsList ...

Utilizing Vanilla JavaScript to retrieve information from a HTML table

I am currently running my website on XAMPP and I have a database connection set up that I can use. In my database, I have three drop-down menus labeled Translations, Books, and Chapters where the data for each is stored. My goal is to utilize Vanilla JS ...

Client.db is undefined error encountered in MongoDB backend API

I'm having trouble retrieving data from a collection in my MongoDB backend. Every time I try, I encounter an error stating that the client is not defined. Has anyone else experienced this issue and knows how to resolve it? Error: Client is not define ...

Unable to find component: "wrestler-choice-box". If this is a built-in custom element, please ensure it is not included in component resolution

In my attempt to achieve a specific goal, I have an array of data that I want to incorporate into my HTML document along with a Vue component containing a template. My intention is to utilize list rendering so that the names and images from this array bind ...

Having difficulty implementing infinite-scroll functionality with angular-meteor collection filtering

Currently, I am in the process of developing a dynamic photo database that allows users to browse through photos, apply filters by user, select multiple categories of interest, and sort the filtered data based on different criteria such as date or number o ...