数组 – ng-init在array.splice之后错误计算别名索引

我遇到了与ng-init相关的奇怪行为,任何帮助都将不胜感激.

我有一个模型对象,它具有flats属性,它是一个扁平对象数组.每个平面对象都有房间属性,这是一系列房间对象.

我试图展示平面和房间如下;

<table ng-repeat="flat in model.flats" ng-init="flatIndex = $index">
<thead>
<tr>
    <td>{{flatIndex+1}}. {{flat.name}}</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="room in flat.rooms" ng-init="roomIndex = $index">
    <td>{{roomIndex+1}}. {{room.name}}</td>
</tr>
</tbody>
</table>

如果我使用array.splice删除平面或房间flatIndex和roomIndex变量似乎没有正确更新,即使$index和ui正确更新.

您可以看到问题here正在运行中.

尝试通过单击删除链接删除第1,第2或第3个单位或房间对象.从数组中删除最后一个对象并不能真正揭示问题.

任何变通办法也将不胜感激.

最佳答案 当您使用ng-init时,这是一种已知行为,不会监视由ng-init设置的范围属性值,并且当您从数组中删除项目以反映刷新的索引位置时,它们不会更新.所以不要使用ng-init,而只需使用$index(deleteFlat($index))和平面对象引用(以获取房间deleteRoom(flat,$index)).

<table ng-repeat="flat in model.flats track by flat.id">
<thead>
    <tr>
        <td colspan="2">{{$index+1}}. {{flat.name}}</td>
        <td><a href="#" ng-click="deleteFlat($index)">DELETE FLAT</a></td>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="room in flat.rooms  track by room.id">
        <td>&nbsp;</td>
        <td>{{$index+1}}. {{room.name}}</td>
        <td><a href="#" ng-click="deleteRoom(flat,$index)">DELETE ROOM</a></td>
    </tr>
</tbody>
</table>

$scope.deleteFlat = function(flatIndex){
    $scope.model.flats.splice(flatIndex,1);
};

$scope.deleteRoom = function(flat,roomIndex){
   flat.rooms.splice(roomIndex,1);
};

Plnkr

或者最好使用id本身,deleteFlat(flat.id)和deleteRoom(room.id,flat).

<table ng-repeat="flat in model.flats track by flat.id">
<thead>
    <tr>
        <td colspan="2">{{$index + 1}}. {{flat.name}}</td>
        <td><a href="#" ng-click="deleteFlat(flat.id)">DELETE FLAT</a></td>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="room in flat.rooms track by room.id">
        <td>&nbsp;</td>
        <td>{{$index+1}}. {{room.name}}</td>
        <td><a href="#" ng-click="deleteRoom(room.id, flat)">DELETE ROOM</a></td>
    </tr>
</tbody>
</table>

$scope.deleteFlat = function(flatId){
  $scope.model.flats.splice(_getItemIndex(flatId, $scope.model.flats), 1);
};

$scope.deleteRoom = function(roomId, flat){
  flat.rooms.splice(_getItemIndex(roomId, flat.rooms), 1);
};


function _getItemIndex(imtId, itms){
  var id ;
  itms.some(function(itm, idx){
      return (itm.id === imtId) && (id = idx)
   });
   return id;
}

Plnkr2

点赞