When I make edits to a specific item, the original collection will automatically update with the changes and will keep adding as I click

Whenever I click on an item in collection A and move it to collection B, any changes made to the Value of Collection B also affect the item in collection A. How can this issue be resolved?

The sum exceeds the limit after multiple clicks.

  var app = angular.module("RodoApp", []);

  app.controller("RodoController", function ($scope, $http) {
    $scope.data_List = [{Value: 100 },
                        {Value: 200},
                        {Value: 300},];
    $scope.List_Add = [];
    $scope.click_Add = function (data) {
      if ($scope.List_Add.indexOf(data) == -1) {
        $scope.List_Add.push(data);
    $scope.Sum = () => $scope.List_Add.reduce((Value, b) => { return Value + b.Value; }, 0);  //Calculate SUM

      }
    }

    $scope.click_Update = function (data, newValue) {
      data.Value = newValue;
    }
  });
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="RodoApp" ng-controller="RodoController">
  <table class="table table-hover table-striped">
    <tr ng-repeat="data in data_List">
      <td ng-click="click_Add(data)">{{ data.Value }}</td>
    </tr>
  </table>
  <hr/>
  <table class="table table-hover table-striped">
    <tr ng-repeat="data in List_Add">
      <td>
        <a href="#" ng-show="!show_Update" ng-click="model_Value = data.Value; show_Update = true">{{ data.Value }}</a>
        <div ng-show="show_Update">
          <input type="text" ng-model="model_Value">
          <input type="button" value="Save" ng-click="click_Update(data, model_Value); show_Update = false;">
        </div>
      </td>
    </tr>
<tr>
  <td>Sum: {{Sum()}}</td>
</tr>
  </table>
</body>

For more information, visit CodePen

After numerous clicks on an item in collection B, the total sum continues to increase indefinitely.

https://i.sstatic.net/MLCdK.png

Answer №1

When you insert data into List_Add, both arrays will reference the same object. To avoid this, it is recommended to duplicate the data using either the spread syntax or Object.assign() method before adding it to List_Add.

$scope.List_Add.push({ ...data })

or

$scope.List_Add.push(Object.assign({}, data))

Modified code snippet:

var app = angular.module("RodoApp", []);

app.controller("RodoController", function($scope, $http) {
  $scope.data_List = [{Value: 100 }, {Value: 200}, {Value: 300},];
  $scope.List_Add = [];
  $scope.click_Add = function(data) {
    if ($scope.List_Add.indexOf(data) == -1) {
      $scope.List_Add.push({ ...data});
    }
  }

  $scope.click_Update = function(data, newValue) {
    data.Value = newValue;
  }
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="RodoApp" ng-controller="RodoController">
  <table class="table table-hover table-striped">
    <tr ng-repeat="data in data_List">
      <td ng-click="click_Add(data)">{{ data.Value }}</td>
    </tr>
  </table>
  <hr/>
  <table class="table table-hover table-striped">
    <tr ng-repeat="data in List_Add">
      <td>
        <a href="#" ng-show="!show_Update" ng-click="model_Value = data.Value; show_Update = true">{{ data.Value }}</a>
        <div ng-show="show_Update">
          <input type="text" ng-model="model_Value">
          <input type="button" value="Save" ng-click="click_Update(data, model_Value); show_Update = false;">
        </div>
      </td>
    </tr>
  </table>
</body>

Additionally, note that indexOf may not work effectively anymore due to the cloning process. It is suggested to assign a unique id property to each object for identification and use some method to check if an object is already present in List_Add

if (!$scope.List_Add.some(o => o.id === data.id)) { }

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

Fb.UI Dialogs now appearing in Popups rather than an iframe (part 2)

Here is a related issue that I came across: With the assistance of OffBySome, I managed to display my FB.ui dialog boxes in an iframe rather than as pop-ups. However, now I am experiencing an issue where the dialog appears but the loading throbber continu ...

a script in JavaScript that retrieves the selected value from a radio button box

I have an AJAX table where I need to highlight one of the rows with a radio box on the left side. However, I lack proficiency in JavaScript and would like assistance in retrieving the value of the radio box by its ID from this table once it has been select ...

The readline interface in Node that echoes each character multiple times

After creating a node readline interface for my project, I encountered an unusual issue. this.io = readline.createInterface({ input: process.stdin, output: process.stdout, completer:(line:string) => { //adapted from Node docs ...

Combining plugin setups and functionalities into a unified script

When it comes to grouping plugin initializations and scripts in a website, I often have a "tools.js" file that contains various functions, click events, and more. I prefer keeping all these script calls centralized in one file for simplicity, organization, ...

Adding URIs to a post request using JavaScript

I'm struggling to understand how to include URIs in a POST request, similar to this API request: link to example This is my current request, but it's not functioning properly fetch(endPoint, { method: "POST", headers: { Authorization ...

Clicking outside the div will cause the div to be hidden

Looking for some help with a jQuery issue. I have a pop-up that opens when a div is clicked, but I want it to close when clicking outside of the div instead of just on the close button. <a class="close-up" href="#" onclick="popup('popUpDiv')" ...

Consistently encountering errors when trying to install npm

While attempting to install the Search git whodotheyserve. com application, I encountered a persistent error that shows up regardless of what troubleshooting steps I take. I have experimented with different versions of npm, all of which are successfully in ...

Caution: Attempting to access a non-existent 'sequelize' property within a circular dependency in the module exports

Issue Nodemon server.js [nodemon] 2.0.15 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node server.js` Warning: connect.session() MemoryStore is not designe ...

"Incorporate information from a separate VueJs object to enhance your data analysis

Just a quick question here. I have an object with the following value: data() { return { nation: { CZ: require("../../../../../svg/czech-flag.svg"), } }; }, Then I have an API object (FYI, the API is working fine) doctor ...

The Strophe.muc plugin and backbone improper binding of callbacks

Following the initial group message, I'm experiencing an issue with the strophe.muc plugin not responding to subsequent messages. Although I receive the first presence, message, and roster from the room, any additional messages and presence stanzas do ...

If the ng-model value is 0, the HTML placeholder will take precedence and override it

Is there a way to customize ng-model so that it shows the placeholder value instead of the actual ng-model value when the value is 0? The UX requires one value for ng-model, while the business logic requires another. How can this be achieved? For example ...

Convert time display to a 24-hour format using JavaScript

I managed to convert the time format from GMT to my browser's local time using the following JavaScript code: var newDate = new Date(timeFromat); timeFormat = newDate.toLocaleString(); Now, I want to change the time format to a 24-hour clock format ...

Iterate through every row in the table in order to carry out a mathematical operation

I have created a jQuery function to add a table dynamically: $(document).on('click', '.add', function(){ var html = ''; html += '<tbody><tr>'; html += '<td><select name="product_name[]" cla ...

Can Vue.js support associative arrays without resorting to objects?

Is there a way to create an associative array without causing an error due to the lambda sign in the syntax? I prefer not to use an object because the key must be a string with capital letters and spaces. <script> export default { name: 'Vu ...

Having difficulty sending a message from an AngularJS application to an Angular 10 application through an iframe

I have two applications running locally - one is an AngularJS application and the other is an Angular 10 application. I am trying to access a page from the Angular 10 application using an iframe and send a message to it from the AngularJS application. How ...

"Utilizing jQuery to integrate an Ajax-powered Gauge using Google Visualization API

I need help creating a dynamic dashboard gauge that updates using ajax. The code snippet below shows what I have so far, but I'm struggling with updating the gauge itself. Any advice or suggestions on how to achieve this? google.load('v ...

What is the process of specifying that an Angular directive must act as a child directive within a particular directive in Angular?

I am currently developing a directive for AngularJS. How can I specifically configure it to require being a child of directiveA? For instance, consider the following example: <my-modal> <m-header>Header</m-header> </my-modal> ...

Steps for sending a value to an AngularJS $http success function

I have a question that is very much like the one posed here: How to pass a value to an AngularJS $http success callback As per Angular.js The $http legacy promise methods success and error have been deprecated. You should use the standard then method ...

VeeValidate3: Unique validation will always return true upon submission

I have integrated Vue.js 2 and VeeValidate3 to validate my form. In addition, the form makes an axios call to verify if the username is already in use. If it is, the validation should be set to false. Everything seems to be working fine so far. I am able ...

What is the best way to transform a text file into an array of objects?

I have a text that resembles the following structure: {"age": "52", "id": 1, "name": "Hulk"} {"age": "33", "id": 2, "name": "Iron Man"} My goal is to parse ...