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}