Ng-init calculates an alias index after array.splice

I came across strange behavior related to ng-init, any help would be appreciated.

I have a model object that has the flats property, which is an array of flat objects. Each flat object has a room property, which is an array of room objects.

I am trying to display flat and rooms as follows:

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

If I delete an apartment or room with array.splice flatIndexand roomIndex, the variables do not seem to be updated properly, even if $indexui are updated correctly.

You can see the problem here in action.

1-, 2- 3- , . .

.

+4
1

ng-init, , ng-init, , , . ng-init, $index (deleteFlat($index)) flat ( 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

, 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

+2

All Articles