我想使用modal从ng-repeat中删除元素。这是我的看法
<table class="table">
<tr>
<td ng-repeat="u in usersHotel" ng-show="detail"> ## Heading ## {{u.hotel.name}}
<i class="fa fa-pencil"></i>
<i class="fa fa-trash-o" data-toggle="modal" data-target="#myModal">
<div class="modal fade" tabindex="-1" role="dialog" aria-
labelledby="mySmallModalLabel" aria-hidden="true" id="myModal">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">are you sure you want to delete this hotel ?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-green" id="modal-btn-si" ng-click="deleteUserHotel(u)">Yes</button>
<button type="button" class="btn btn-default" id="modal-btn-no">No</button>
</div>
</div>
</div>
</div>
</i>
</td>
</tr>
</table>
这是我的控制器:
$scope.deleteUserHotel = function(userHotel){
UsersService.deleteUserHotel(userHotel).then( function(d) {
$scope.users = d;
$scope.getHotelByUserName($scope.newUser.userId);
},
function(errResponse){
console.error('Error while deleting userHotel');
}
);
};
service.js:
service.deleteUserHotel = function(userHotel){
var id=userHotel.id;
return $http.post(_contextPath + '/deleteUserHotel', id ).then(
function(response) {
return response.data;
}, function(errResponse) {
console.error('Error while deleting UserHotel');
return $q.reject(errResponse);
});
};
我的问题是,当我想要删除第二个元素或第三个元素时,这个代码总是删除第一个元素抱歉这个问题,但我需要帮助。谢谢提前。
答案 0 :(得分:0)
您正在为每个u
创建一个模态,但对模态(id
)始终使用相同的myModal
。
当点击打开模态时,该函数会搜索id
与data-target
属性相同的模态的第一次出现。因为它们都是相同的,所以它总是打开第一行的模态,因此总是删除第一个酒店。
你必须在动态创建模态的id
并根据id
定位它们。您可以使用ng-repeat
的$index
属性(或者更好地使用id
对象的u
,如#myModal{{u.id}}
中所示,如果它们是唯一的在数组中):
<table class="table">
<tr>
<td ng-repeat="u in usersHotel" ng-show="detail"> ## Heading ## {{u.hotel.name}}
<i class="fa fa-pencil"></i>
<i class="fa fa-trash-o" data-toggle="modal" data-target="#myModal{{$index}}">
<div class="modal fade" tabindex="-1" role="dialog" aria-
labelledby="mySmallModalLabel" aria-hidden="true" id="myModal{{$index}}">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">are you sure you want to delete this hotel ?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-green" id="modal-btn-si" ng-click="deleteUserHotel(u)">Yes</button>
<button type="button" class="btn btn-default" id="modal-btn-no">No</button>
</div>
</div>
</div>
</div>
</i>
</td>
</tr>
</table>
请注意,切换的data-target
和模式的id
都使用$index
生成新的模式id
。