Refreshing data and manipulating arrays using AngularJS

Currently, I am developing an application utilizing AngularJS and LocalStorage. I've encountered a challenge that seems a bit too intricate for me to handle.

The app involves managing lists of people with the ability to add arrays of names. The process is as follows: I select X names, click "add," which creates an object in an array, resets the list, and allows me to repeat the process by choosing X names again and clicking "add."

Below is how I generate the temporary array that is then stored in LocalStorage:

HTML:

<form>
  <div class="col-md-3" ng-repeat="staff in stafflist | orderBy: 'name'">
    <button class="btn form-control" ng-show="!staff.chosen" ng-click="pushStaff(staff)">{{staff.name}}</button>
    <button class="btn btn-primary form-control" ng-show="staff.chosen" ng-click="unpushStaff(staff)">{{staff.name}}</button>
  </div>
  <button class="btn ng-click="addRecord()">Add passengers</button>
</form>

JS:

$scope.paxlist = [];
$scope.pushStaff = function (staff) {
    staff.chosen = true;
    $scope.paxlist.push(staff);
    console.log($scope.paxlist);
};

$scope.unpushStaff = function (staff) {
    staff.chosen = false;

    var index=$scope.paxlist.indexOf(staff)
    $scope.paxlist.splice(index,1);     
    console.log($scope.paxlist);
}

The issue I'm facing is that while I can successfully create objects in the array, when adding an object, the selected items from the list of names do not reset, causing them to remain pre-selected when adding the next object. Furthermore, each new object added remains linked to the last one, leading to modifications affecting both. This complication also hinders the possibility of implementing an editing feature for each object in the array.

I have shared a Plnkr demonstrating the problem.

If you have any insights on this issue, it would be greatly appreciated.

Answer №1

Ensure to reset the chosen property in the addRecord function.

$scope.addRecord = function () {
    $scope.recordlist.push({ pax: angular.copy($scope.paxlist) });

    jsonToRecordLocalStorage($scope.recordlist);

    $scope.editItem = false;
    $scope.paxlist  = [];

    $scope.stafflist.forEach(function (el) {
      el.chosen = false;
    });
};

See a demo here: http://plnkr.co/edit/vV8OuKiTKYkFyy7SrjOS?p=preview

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

TinyMCE - The control with the name 'content' is considered invalid and cannot receive focus

I am utilizing TinyMCE 4 and here is the code snippet for it: <script type="text/javascript" src="//cdn.tinymce.com/4/tinymce.min.js"></script> <script> tinymce.init({ selector: 'textarea[name=content]', ...

Working with Firebase and handling asynchronous data retrieval: Implement success and error callbacks with the

I'm currently working on an Angular application that includes the following function: $scope.retrieveProjectData = function() { $scope.projectNumberNoChange = false; // Only fetch data if the ProjectNumber has changed if (cur ...

When the webpage is refreshed, a PHP code embedded within JavaScript is executed instead of waiting for a

This particular code is designed to toggle the chat feature on and off. The issue I am encountering is that it automatically toggles the chat on or off each time the page is refreshed. Ideally, it should only trigger when a user clicks on a specific link ...

Tips for changing a scope value in a different controller

I have two controllers and a factory. My goal is to update a value in the factory from controller1 and have it reflected on controller2, which controls my sidebar. Controller 1: $scope.proyectoLoad = ProyectoLoadedFactory.getProyectoLoaded(); $scope ...

What changes can I make to this jquery code to utilize a background image instead of a background color?

Can someone help me modify this snippet to set a background-image instead of changing the background color? <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("#button_layer").hide(); $("#im ...

Renew the php blade foreach loop using jQuery to update data live

I have a foreach cycle in my HTML, and at one point, some data is posted from JavaScript. I would like to append it once it is added to the database. I need to find a way to refresh the foreach loop without reloading the entire page (I could simply use ap ...

The significance of the "$=" or "?=" symbols in lit-element illustrations

I'm struggling to comprehend the purpose of ?= or $= in these two instances: First Example: Lit-Element README <div id="box" class$="${this.uppercase ? 'uppercase' : ''}"> <slot>Hello World</slot> </div> ...

Integrating Python Script with User Input and Output within a JavaScript Web Application

I have an existing JS website that requires additional functionality, and after some research I believe Python is the best tool to handle the necessary calculations. My goal is for users to input information that will then be used as input for my Python ...

Tips for performing matrix manipulation in Matlab:

I have two matrices in Matlab: matrix A of size m x n and matrix b of size 1 x n. Matrix b is structured such that it contains sequences of increasing values up to a certain number k (e.g. b = [1 1 1 2 2 3], n = 6). My goal is to iterate through each row ...

How can I display components using Angular CLI 5 without any visual output?

The index.html page is not displaying anything, not even the "App works" message that should appear in a basic initial project ng --version Angular CLI: 1.6.0 Node: 8.9.1 OS: darwin x64 Angular: 5.1.0 ... animations, common, compiler, compiler-cli, core, ...

Handling error reporting using JSON in jQuery AJAX post success

UPDATE: I have resolved the PHP errors mentioned in previous Answers, however, the issue still persists. I am attempting to implement an error message display in case of a failed POST request and a success message for successfully completed requests. Curr ...

Attempting to showcase JSON response within an HTML page using JavaScript

Can anyone help me troubleshoot my code for displaying JSON data on a web page? Here's what I have so far: <button type="submit" onclick="javascript:send()">call</button> <div id="div"></div> <script type="text/javascript ...

Determining the file extension type of an uploaded file using JavaScript

In my new file upload system, users have the option to upload both images and videos. After uploading a file, I provide a preview of the uploaded content. Desired Outcome: My goal is to display only ONE preview based on the type of file (image or video). ...

Chrome and Firefox provide excellent compatibility for running JavaScript, whereas Safari may encounter some issues. Opera's performance with JavaScript can be quirky

Disclaimer: I'm new to web design and development. I have encountered an issue with posting information from a form built on CodeIgniter using jQuery. The form posts successfully in Chrome and Firefox, with the current page automatically reloading. H ...

extracting a particular value from a JSON object using JavaScript

How can I extract a specific value from my JSON file using Node.js? var request = require("request"); var options = { method: "GET", url: "URL of my database", headers: { "cache-control": "no-cache&qu ...

Automated Desk: adjust page through programming

I am currently utilizing Smart Table and I would like to automatically navigate to a specific page once the controller has been created and the table is displayed. After searching on stackoverflow, I came across this code snippet that allows me to achieve ...

Body section CSS selector

Can a CSS selector be included within the body section of an HTML document? Here's an example of my code (although it is not functioning as expected): <html> <head> </head> <body> <div style= "a[target=_blank] {backgroun ...

Avoiding jQuery selector

What is the reason for the selector working in the first example but failing in the second one? Check out jsfiddle. <div id="hello[1][2]_world">&nbsp;</div> <textarea id="console"></textarea> <script> $(document).re ...

Struggling with consolidating values in an array of objects - seeking assistance with Javascript

Currently, I am handling a project where I receive data in the form of an Object Array. My task is to merge values with the same key into one key and convert the values into an array of strings. Below is the sample data I am working with: inputArray = [ ...

Generate an array using the properties of an object

Seeking a more efficient way to configure settings for an app using objects? Consider starting with the following object: var obj = { property_one: 3; property_two: 2; property_three: 1; } And transforming it into the desired array format: v ...