簡體   English   中英

AngularJS刪除范圍內數組的最后一個元素

[英]AngularJS remove last element of array in scope

我在Angular中有我的控制器,其中包含一個數組和一個delete方法

function($scope, $http){
    $scope.arrayOfObjects = [];
    $scope.remove = function(obj){
        var i = $scope.arrayOfObjects.indexOf(obj);
        if( i > -1 ){
            $scope.arrayOfObjects.splice(i, 1);
        }
    }
// Some other things
}

HTML

<a href ng-repeat="(key, obj) in arrayOfObjects track by $index">{{obj.id}}

<button type="button" role="button" class="btn btn-default" ng-click="remove(obj)">
   <i class="fa fa-trash"></i>
   <span>Delete</span>
</button>

</a>

現在,當我刪除除上一個對象以外的其他對象時,一切正常。 當用戶按下最后一個對象的刪除按鈕時,該頁面將重定向到localhost:3000 /#,該主機未映射到任何內容,而我得到了一個空白頁面。

有沒有人遇到過這種行為?

當其他答案解決您的鏈接/重定向問題時,可以通過在錨標記中沒有其他可單擊項來解決該問題,但更大的問題是您使用了錯誤的語法來遍歷數組的對象。

要遍歷數組,您需要這樣做:

ng-repeat="obj in arrayOfObjects"

您使用的語法用於迭代單個對象的屬性。 keyvalue是傳遞給中繼器的參數

ng-repeat="(key, value) in object"

您最想要的是這樣的東西:

<div ng-repeat="obj in arrayOfObjects">
  {{obj.id}}
  <button ng-click="remove(obj)">Delete</button>
</div>

codepen

您可以使用“過濾器”將所需的所有迭代恢復到原始范圍,如下所示:

        $scope.remove = function (objs) {
            $scope.objs = objs.filter(function (obj) {
               //Here you remove the item you do not want   
               return obj;
            });
        };

HTML:

    <button class="btn btn-danger btn-block" ng-click="remove(objs)">Delete</button>

可以使用pop()刪除最后一個元素,並返回該元素,例如$scope.arrayOfObjects.pop()

 angular.module('app', []) .controller('mycontroller', function($scope) { $scope.arrayOfObjects = [{ id: 1 }, { id: 2 }, { id: 3 }] }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="mycontroller"> <button ng-click="arrayOfObjects.pop()">remove in inline</button> <ul> <li ng-repeat="myobj in arrayOfObjects">{{myobj.id}}</li> </ul> </div> 

暫無
暫無

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

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