这是您使用时的已知行为,不监视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> </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> </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