In AngularJS, the placement of an element within an array is determined by its index position, without altering or replacing any other

Creating dynamic select boxes using ng-repeat and passing index values for each select box via ng-change.

This is the HTML code:

    <thead>
      <th ng-repeat="l in labels"><div style="width:200px;"></div>{{l.labelname_en}}
      </th>
   </thead>

   <tbody>
      <td ng-repeat="e in excelvalues">
          <select name="selectExcel" class="form-control"  ng-model="selectedExcel" ng-options="excel for excel in excelvalues" ng-change="change(selectedExcel,$index)">
          </select>
      </td>
  </tbody>

Here is the JavaScript code:

$scope.change = function(excel,index){

            var data = {
                index:index,
                risk_disc_en:excel
            };
           $scope.arr.splice(index,1,data);
}

Screen Capture:

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

The index value is used to ensure uniqueness. For example, selecting the 1st select box will result in an array like below:

[{"index":0,"risk_disc_en":"Risk Description"}]

Subsequently, selecting the 3rd select box will update the array as shown:

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

[{"index":0,"risk_disc_en":"Risk Description"},{"index":2,"risk_disc_en":"Impact"}]

Please note: The first element has an index of 0 because it was selected first. Similarly, the second element's index is 2 due to selecting the 3rd box instead of the 2nd one.

If a new index value is selected, it should be inserted at the correct position. If the index already exists, the corresponding element with the same index will be updated or replaced.

Examples:

Case 1: arr={0,2} Inserting 1 should result in arr={0,1,2}. However, the current behavior replaces the element resulting in arr={0,1}

Case 2: arr={0,2} Reinserting 2 should replace the element, leaving the array as arr={0,2}

Answer №1

To keep track of selected options and sort them, you can utilize an Object as a map and then organize the object values to produce a sorted array.

$scope = {};
$scope.map = {};
$scope.change = function(selection, index) {
  var data = {
    index: index,
    choice: selection
  };
  
  $scope.map[index] = data;
  $scope.array = Object.values($scope.map).sort(function(a,b){
    return a.value - b.value;
  })
}

$scope.change("option1", 1);
$scope.change("option3", 3);
$scope.change("option5", 5);

console.log($scope.array);

Answer №2

It is suggested to first search for the item before taking any action. If the item is found, no further steps are needed. However, if it is not found, you can insert the item at a specific index by following this code snippet:

$scope.updateItem = function(itemData, index) {
  var newItem = {
    index: index,
    data: itemData
  };
  
  var existingIndex = $scope.itemArray.findIndex(item => item.index === index);
  
  if (existingIndex === -1) {
    $scope.itemArray.splice(index, 0, newItem);
  } else {
    $scope.itemArray.splice(index, 1, newItem);
  }
}

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

Swapping data within a powershell object

Struggling with setting the HA datastores in my VMware environment using PowerShell. I'm having difficulty replacing a specific value. $Cluster = Get-Cluster $ClusterName | Get-View $HAInfo = $Cluster.Configuration.DasConfig The output of $HAinfo is ...

What makes the syntax 2[myArray] valid in C?

Unique Question Why is a[5] equal to 5[a] in C arrays? Consider the following array: myArray[5] = { 0, 1, 2, 3, 4 }; An element can be accessed as: 2[myArray] What is the reasoning behind being able to access elements this way? I'm puzzled b ...

Creating a user-friendly error message on the interface using JavaScript

I have implemented a table that showcases data from the Geonames API. Currently, I am working on creating a function to handle errors when the user forgets to fill in the input fields and then trigger an alert on the interface. The code snippet below sho ...

Sending back an array within the onOpen function

I am currently in the process of developing a chat application. At this stage, users are able to send messages to each other and I have successfully stored these messages in my database. Now, my objective is to display the stored messages from the database ...

Updating an Element in an Array with Mongoose

Is there a more efficient way to update an existing element in an array without fetching the database multiple times? If you have any suggestions, I would greatly appreciate it. Thank you! const updateStock = async (symbol, webApiData) => { try { ...

Substitute numerical characters with dots

Seeking a solution to replace certain ID numbers in my system with clickable numbers that open the related record. The challenge arises when the IDs are in the format of 123.456.789, as my regex also matches IP addresses like 123.[123.123.123] (where the [ ...

Anticipating the arrival of a JSON object, array, or literal

I am working with 3 specific files: index.html js/main.js json.json The file named "json.json" contains the following code snippet: data = '[ {"name":"John","guests":3,"status":"true"}, {"name":"Mike","guests":5,"status":" ...

Safari seems to be having trouble locating the variable MediaRecorder

I've encountered an issue while working on a video chat application and attempting to record the video. Specifically, I'm struggling with recording the local Stream or Remote Stream in the Safari browser. An error message stating "can't find ...

Creating a JavaScript and C# popup for deleting records in asp.net

I'm struggling a bit with understanding how server-side deletion works. I know how to use MessageBox, but it's not the best approach. I've been advised to use a popup on the server side. What I'm trying to achieve is that when you clic ...

Incorporate JavaScript objects as data values within a MySQL query statement

Currently, I am utilizing a pool to query mySQL on nodejs and everything is functioning smoothly. let values = [1, 2, 3]; DB.pool.query('SELECT * FROM table_name WHERE col1 = ? AND col2 = ? AND col3 = ?', values, (err, rows) => { //Perfor ...

Explore the functionality of the Bootstrap 3 modal by scrolling through

I'm trying to get my modal to automatically scroll down to the chart area when I click on the calculate button. Here's the code I have: $('#budgetCalModal').animate({ scrollTop: $("#result").offset().top }, 1000); However, it does ...

Troubleshooting issue with Angular directive and $timeout functionality malfunctioning in Internet Explorer

I have developed a straightforward directive that scans the DOM to locate and hide matching input fields (The client wishes to be able to dynamically hide certain fields). The directive functions properly in Chrome, but encounters issues in IE11. While ng- ...

Encountering a "MissingSchemaError" while attempting to populate the database with mongoose-seeder

I am facing an issue while trying to populate a database using mongoose-seeder. Despite setting up the schema correctly, I keep encountering a MissingSchemaError which has left me puzzled. Here is a snippet from the file where I define the schema: const m ...

Designing a Database for a Symmetric Covariance Matrix with Fixed Size

As someone new to relational database design, I am faced with the challenge of storing a 9x9 covariance matrix in a table. This matrix contains x, y, z terms of position, velocity, and acceleration. The structure looks like this: PosX PosY PosZ . ...

What is the best way to adjust the vertical margin in a vis.js timeline?

The vis.js timeline sets a margin of 5px in each row using inline styles that are controlled programmatically by the library. The height, top position, and transform of each item within the row are specified by the library as well. Attempting to manually ...

Pass a collection of string values from Visual FoxPro to a dynamically linked library built in Delphi

Recently, I have developed a DLL in Delphi that needs to accept an array of strings from Visual Fox Pro as one of its parameters. Unfortunately, my attempts to pass this data have resulted in a "Declare DLL call caused an exception" error. It has left me w ...

How can I stop the popper position from changing while scrolling?

Is there a way to keep the popper element's position fixed without it being affected by future updates, all while still maintaining the scroll listener? The gif demonstrates my current sticky popper setup, but I would prefer it to remain static and n ...

Formatting strings with positive or negative numbers can be achieved using Utilities.formatString

Looking to enhance the visual representation of numeric string data by displaying it in different colors based on whether the number is positive or negative. Current code snippet: var url = 'https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxx ...

Is this jQuery script not functioning properly?

I came across this code on jsfiddle, and I really want to incorporate it into my PHP file. However, when I tried to do so, it didn't work even though I simply copied and pasted the code without making any changes. Here is my code: <!DOCTYPE html& ...

The npm outdated -g command is producing an error message that states "Unable to read the length property of undefined"

I am currently facing an issue while trying to check the version status of my npm installed global packages. When I run the command npm outdated -g --depth=0 in the terminal, I encounter the following error: npm ERR! Cannot read property 'length&apos ...