简体   繁体   中英

I can´t remove the last item of array

I can remove any item of array unless the last one. I also use angularjs to show information in the view. I don´t know what is happening with the last item of this array. Please, anyone can help me?

Here is 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>

Here is 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();
        };

Or Plunker

In your HTML you are preventing the deletion of the last element:

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

documentos.length > 1 means "hide when it reaches one item in the array".

It should be documentos.length == 0 .

It's either this or your index value starts from 1 and not from 0.

The simplest solution would be to change your remove function to take in the document instead of the index. Try this:

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

in view:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM