繁体   English   中英

在数组中插入元素取决于其索引位置,而不替换或更改angularjs中的其他元素

[英]Insert element in array depends on its index position without replace or change other element in angularjs

我有使用ng-repeat的动态选择框。 然后我通过ng-change传递了每个选择框的索引值。

这是我的html:

    <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>

这是我的js:

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

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

这是屏幕:

在此处输入图片说明

在此,我使用索引值使其成为唯一。 如果我选择了第一个选择框,数组将像

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

在那之后,如果我选择了第三个选择框,数组将像

在此处输入图片说明

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

注意:第一个元素的索引为0,因为我选择了第一个框。 然后,第二个元素的索引为2,因为我选择了第三个框而不是第二个框。

之后,我在第二个框中选择了控制台中的数组值

在此处输入图片说明

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

数组位置1 {"index":2,"risk_disc_en":"Impact"}的元素替换为{"index":1,"risk_disc_en":"Probability"}

但我想要输出数组像

[{"index":0,"risk_disc_en":"RiskDescription"},`{"index":1,"risk_disc_en":"Probability"},{"index":2,"risk_disc_en":"Impact"}]`

如果索引值之前不存在,则元素应插入正确的位置。 如果存在,它将更新或替换具有相同索引值的相应元素。

例如 :

情况1: arr={0,2} ,我尝试插入1,它应该像arr={0,1,2} 就我而言,它替换了元素,看起来像arr={0,1}

情况2: arr={0,2} ,我尝试再次插入2,它应该替换并排列为arr={0,2}

我认为最好先搜索该项目。 如果您收到了该物品,则无需执行任何操作。 但是,如果没有,则可以将项目推送到指定的索引上:

 $scope.change = function(excel, index) { var data = { index: index, risk_disc_en: excel }; var index = $scope.arr.findIndex(item => item.index === index); if (index === -1) { $scope.arr.splice(index, 0, data); } else { $scope.arr.splice(index, 1, data); } } 

您可以使用Object作为映射来跟踪所选选项,并对对象值进行排序以获得排序后的数组。

 $scope = {}; $scope.map = {}; $scope.change = function(excel, index) { var data = { index: index, risk_disc_en: excel }; $scope.map[index] = data; $scope.arr = Object.values($scope.map).sort(function(a,b){ return a.value - b.value; }) } $scope.change("item2", 2); $scope.change("item3", 3); $scope.change("item0", 0); console.log($scope.arr); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM