角度在ng-repeat(MEAN-Stack)中传递错误的对象

Angular passes wrong object in ng-repeat (MEAN-Stack)

本文关键字:错误 对象 ng-repeat MEAN-Stack      更新时间:2023-09-26

我正在为我的学院建立一个管理考试的平台。我使用平均堆栈。

除了删除"klausur"(德语考试)外,一切正常。守则如下。如果我在表格的任何对象上单击最后一个链接(使用"删除克劳苏尔(klausur)"单击),而不是瞬时对象,而是我的最后一个链接将在我的表格中删除。在数据库内部,删除了右侧的数据库。如果我再次单击相同的按钮,服务器会崩溃,并且因为它尝试再次删除相同的ID,从而给我带来了有关空对象的问题。

<table class="table table-hover table-striped">
            <thead>
            <th>ID</th>
            <th>Name</th>
            <th>Datum</th>
            <th>Semester</th>
            <th>Aufgabenzahl</th>
            <th>Teilnehmer</th>
            <th>Aktionen</th>
            </thead>
            <tbody>
            <tr ng-repeat="klausur in klausuren">
                <td>{{klausur._id}}</td>
                <td>{{klausur.name}}</td>
                <td>{{klausur.gehaltenAm | date:'dd.MM.yy'}}
                    <br/>{{klausur.gehaltenAm | date:'H:mm'}}
                </td>
                <td>{{klausur.semester}}</td>
                <td>{{klausur.aufgaben.length}}</td>
                <td>{{klausur.teilnehmer.length}}</td>
                <td><a href="#/klausuren/{{klausur._id}}/edit" class="btn btn-default" style="width:100%">Klausur
                    ändern</a><br/>
                    <a href="" ng-click="deleteKlausur(klausur)" class="btn btn-danger" style="width:100%">Klausur löschen</a></td>
            </tr>
            </tbody>

我的JS(使用角度)脚本如下:

app.controller('KlausurListController', function ($scope, $http) {
$http.get('http://localhost:3000/klausuren').success(function (response) {
    $scope.klausuren = response;
}).error(function (err) {
    $scope.error = err;
});
$scope.deleteKlausur = function (klausur) {
    $http.delete('http://localhost:3000/klausuren/'+ klausur._id).success(function(res){
        $scope.klausuren.pop(klausur);
    });
}});

谢谢你,甚至阅读了整件事!希望你能帮到你!

您正在使用仅删除数组中最后一个元素的pop()

要删除正确的索引,您需要在数组中找到它的索引并使用splice()

$scope.deleteKlausur = function (klausur) {
    $http.delete('http://localhost:3000/klausuren/'+ klausur._id).success(function(res){
        var index = $scope.klausuren.indexOf(klausur);
        if(index !== -1){
           $scope.klausuren.splice(index,1);
        }            
    });
}});