簡體   English   中英

Angular在ng-repeat(MEAN-Stack)中傳遞錯誤的對象

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

我正在建立一個平台來管理我的學院的考試。 我使用MEAN-Stack。

一切正常,除了刪除“ klausur”(德語考試)。 代碼如下。 如果我在表的任何對象上單擊最后一個鏈接(使用“ deleteKlausur(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(使用Angular)腳本如下:

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);
        }            
    });
}});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM