我无法删除最后一项数组

时间:2017-12-29 12:16:28

标签: javascript angularjs

除非最后一个,否则我可以删除任何数组项。我还使用angularjs在视图中显示信息。我不知道这个数组的最后一项发生了什么。拜托,有人可以帮帮我吗?

以下是HTML:

<div class="row">
            <div class="col-md-12">
                <h4><strong>Documento {{index + 1}} de {{documentos.length}}:</strong> {{documentos[index].nome}}</h4>
                <iframe style="background: #ccc;" ng-show="exibirPreview" frameborder="0" ng-src="{{versaoLink}}" width="100%" height="300px"></iframe>
                <div class="alert alert-warning" ng-hide="exibirPreview">
                    @Html.Raw(Resources.Dialog.SignDocuments.TypeDocumentCanNotPreDisplayed)
                </div>
                <hr />
                <div class="pull-right btn-row" ng-show="documentos.length > 1">
                    <button class="btn btn-default" type="button" ng-click="RemoveDoc(index)"><i class="fa fa-fw fa-times"></i> @Resources.Common.RemoveDocList</button>
                </div>
            </div>
        </div>

这是js / angularjs

 $scope.documentos = [
    {nome:"document1", chave: "8F65579E3737706F", extensao:".pdf"},
    {nome:"document2", chave: "8F65579E3730007F", extensao:".pdf"},
    {nome:"document3", chave: "8545579E3737706F", extensao:".pdf"},
    {nome:"document4", chave: "8555579E3730007F", extensao:".pdf"}
]

$scope.ViewLink = function () {
                var versao = $scope.documentos[$scope.index];
                $scope.exibirPreview = versao.extensao == ".pdf" || versao.extensao == ".txt";
                if (!$scope.exibirPreview) {
                    $scope.versaoLink = '';
                } else {
                    $scope.versaoLink = '/Documento/VersaoView?chave=' + versao.chave;
                }
            };
        $scope.ViewLink();

        $scope.RemoveDoc = function (index) {
            $scope.documentos.splice(index, 1);
            $scope.ViewLink();
        };

Plunker

2 个答案:

答案 0 :(得分:1)

在HTML中,您阻止删除最后一个元素:

<div class="pull-right btn-row" ng-show="documentos.length > 1">
   <!-- -->
</div>

documentos.length > 1表示“当它到达数组中的一个项目时隐藏”。

应该是documentos.length == 0

它或者你的index值从1开始而不是从0开始。

答案 1 :(得分:0)

最简单的解决方案是更改删除函数以接收文档而不是索引。试试这个:

$scope.RemoveDoc = function(document) { 
  var index = $scope.documents.indexOf(document);
  $scope.documents.splice(index, 1);     
}

在视图中:

<button class="btn" type="button" ng-click="RemoveDoc(document)">Delete</button>