Replacing old items with new ones: AngularJS now pushes to array in service

I am attempting to update a list in the home.html file and then display the updated list in myOrders.html using ionic and angularjs.

The issue I am facing is that whenever I add a new item to the array, it replaces all the previous items with the new one.

For example:

If I push 'one' -> the array becomes [{'name':'one'}]

If I push 'two' -> the array becomes [{'name':'two'},{'name':'two'}] // should be [{'name':'one'},{'name':'two'}]

If I push 'three' -> the array becomes [{'name':'three'}, {'name':'three'}, {'name':'three'}] // should be [{'name':'one'},{'name':'two'},{'name':'three'}]

Below are the relevant sections of my code.

home.html (Add to list)

<ion-view title="Home">
    <ion-content ng-controller="homeCtrl">
        <form ng-submit="submitForm(product)" class="list">
            <input ng-model="product.name" type="text">
            <input type="submit" value="Search" class="button">
        </form>          
    </ion-content>
</ion-view>

myOrders.html (Display list)

<ion-view title="My Orders">
    <ion-content ng-controller="myOrdersCtrl">
        {{ product }}
    </ion-content>
</ion-view>

controllers.js

angular.module('app.controllers', [])
...
.controller('homeCtrl', function($scope, $state, formData) {
        $scope.product = {};

        $scope.submitForm = function(product) {
            if (product.name) {
                formData.updateForm(product);
                $state.go('menu.myOrders');
            } else {
                alert("Please fill out some information for the user");
            }
        };
    })

.controller('myOrdersCtrl', function($scope, formData) {
    $scope.product = formData.getForm();
})

services.js

angular.module('app.services', [])

.service('formData', [function(){
    return {
        form: [],
        getForm: function() {
            return this.form;
        },
        updateForm: function(item) {
            this.form.push(item);
        }
    }
}]);

Answer №1

Repeatedly inserting the same object into an array will cause all references to point to the same object. This means that updating the object will affect all instances stored in the array.

To avoid this, consider creating a copy of the object before passing it to updateForm().

.controller('homeCtrl', function($scope, $state, formData) {
        $scope.product = {};

        $scope.submitForm = function(product) {
            if (product.name) {
                formData.updateForm(angular.copy(product));
                $state.go('menu.myOrders');
            } else {
                alert("Please fill out some information for the user");
            }
        };
    })

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

Can transitions be applied to links in this manner?

Having an issue with ajax requests, I am currently resorting to using JavaScript linking. This is how I normally link: window.location.href = ('file:///android_asset/www/custom/kontakty.html'); I am curious if it's possible to add a transi ...

Angular table elements can trigger a click event that redirects to a unique URL generated from the ID of the selected element

In the angular table, every element should be clickable. When any element in the table is clicked, it should use its ID to perform a new search and redirect to the URL based on that ID of the clicked element. Below is the JSON data from the initial URL. It ...

Showing undefined or null values in React and JavaScript

My goal is to format undefined or null values by italicizing them. If the value is an empty string, it should be displayed as is. If it has a value, that value should also be displayed as is. However, I am encountering an issue where null or undefined val ...

Hovering over the top menu items in AngularJS will reveal dropdown submenus that will remain visible even when moving the cursor

I am facing an issue where my top menu has links that display a dropdown of additional menu items upon hovering. I have attempted to use onmouseover and onmouseleave events to control the visibility of the sub menu. However, I have encountered a problem ...

Is there a way to convert a URL into a user-friendly json format displayed on a web page

Can someone please help me figure out the proper way to convert this URL into a JSON format that is easily readable using jQuery on an HTML page? ...

Open the navigation menu by clicking on either the navigation links or anywhere outside of it

Seeking a solution for my mobile navigation menu that closes when clicking outside the links or on one of them, without using jQuery. How can I achieve this with JavaScript ES6? Current code snippet: const navSlide = () => { const burger = docum ...

Is there a way to verify whether all elements (text, email, number, and radio) within a specific div have been selected or filled

Is there a way to activate the submit button on a form only when all inputs are checked or not empty? I've come across various snippets on Google and SO that achieve something similar, but they only work for a specific type of input, not taking into ...

Vue.js strange quirks and unpredictable method responses

I am currently working on a Vue.js component that has a simple template. <div @click="createTargets(2)"> text </div> Here is the script file for the component: export default { name: 'test', data() { return { ...

Using Vue Axios to load a Laravel view can be a seamless process that

I'm attempting to create a hyperlink to a Laravel view named faq.blade.php from my Vue component. I've tried using axios, and even though it logs the response in the console, the view isn't loading. How can I resolve this issue? FaqControll ...

Encountering a problem when trying to dynamically change the value in a dropdown menu with Angular.js

Having an issue where two drop down lists have the same value. When I set a value to the first drop down list, the second one also takes that value. Below is my code for reference: <div class="col-md-6"> <div class="input-group bmargindiv1 col-md ...

Vuetify's Handy Helper Classes

Hey everyone, I'm working on a vuetify project and I need to convert inline styles to utility classes (if possible) font-size: 24px; font-weight :600 I checked the documentation and noticed that it only provides options for setting size and weight wi ...

In both Chrome and Edge, the default value for the <select> tag is successfully set, however, this functionality is not working in

I have defined two values in the created method, 2018 and My Name, and assigned them to separate data properties. These data properties are then passed as v-bind to a component. The issue I am facing is that in Chrome and Edge, both values are set as defa ...

When running the command `npx create-react-app client`, an error is thrown stating "Reading properties of undefined is not possible (reading 'isServer')."

Installing packages. Please wait while the necessary packages are being installed. Currently installing react, react-dom, and react-scripts with cra-template... Encountered an error: Unable to read properties of undefined (reading 'isSer ...

The Vue design is not being reflected as expected

Encountering a peculiar issue where the style in my Vue component is not being compiled and applied alongside the template and script. Here's the code snippet: To achieve an animated slide fade effect on hidden text upon clicking a button, I've ...

Invoke the designated JavaScript function within a subordinate <frame>

Below is an example of the standard HTML structure for a parent page named "index.html": <html> <head> <title>test title</title> </head> <frameset cols="150,*"> <frame name="left" src="testleft.html"> ...

Customizing the appearance of selection dropdown options in React

Is it possible to customize the styling of the choices in a React input dropdown? For instance, I am interested in creating an autocomplete dropdown that presents the options neatly arranged in columns. Essentially, I want to design a dropdown data grid t ...

What techniques can be applied to utilize JSON data in order to dynamically create menu components using the map method?

My current challenge involves dynamically generating a set of menu items using data retrieved from a JSON file. I've attempted to achieve this by mapping the values with props, but it seems like I'm overlooking something. Below is the code snipp ...

Guide to keeping numerous movie titles in an array with a for loop in Java

I am currently working on a project for my school assignment, where I need to collect multiple movie titles along with the number of copies of each movie and store them in an array. However, every time I enter a new title, it replaces the previous one(s). ...

AngularJS Unveiled: The Puzzle of ng-if's Digest Loop

I am experiencing an issue with an infinite loop when loading the view. The data is retrieved from an API using ngResource in the controller. The view is being rendered multiple times before displaying correctly. I suspect that there may be a loop occurrin ...

Checkbox value not being accurately retrieved by Struts2 page

I have a form that captures phone information for two different phones, with each phone having its own set of details. If the user enters the same phone number for both phones, the second checkbox is automatically checked using the JavaScript code below: ...