2017-10-21 64 views
1

我有以下列表:如何刪除整個HTML元素

enter image description here

HTML代碼:

<div ng-repeat="alerta in alertas"> 
      <div class="aa" style=" margin-top: 1px;width: 100%; height: 52px;border-bottom: solid 1px #d4d4d4;"> 
       <div class="float-left" style="width: 80%;"> 
        <a href="#" class="item item-icon-left" > 
        <i class="icon ion-alert"></i> 
        {{alerta.desc}} 
        </a> 
       </div> 
       <div class="float-left divdeletea"> 
        <span ng-click="deleteAlert($index)"><img class="imgDelete" src="img/remove-icon.png"></span> 
       </div> 
      </div> 
     </div> 

但只有文字被刪除,請參見下面的圖片: enter image description here

控制器代碼:

$scope.deleteAlert= function(i){ 
    delete $scope.alertas[i]; 

} 

我預期會刪除整個行中的結果: enter image description here

回答

1

delete關鍵字被用於從一個刪除一個屬性目的。所以假設你有一個對象:

let object = {name: 'Pete'}; 
delete object.name; // {} 

你會留下一個空的對象。我從來沒有想過使用它與一個數組,但我假設它將undefined或類似的東西,這仍然是一個有效的數組元素替換元素。

無論如何,從數組中刪除元素的正確方法是使用splice()方法,該方法接受兩個參數,即索引和要刪除的元素數量。所以:

$scope.alertas.splice(index, 1); 
0

嘗試splice從數組中刪除該項目:

$scope.deleteAlert= function(i){ 
    $scope.alertas.splice(i, 1); 
} 
0

這裏有一個例子可以幫助你:

var app = angular.module("myApp", []); 
 
app.controller("myCtrl", function($scope) { 
 
    $scope.alertas = [{desc:"test1"},{desc:"test2"},{desc:"test3"}]; 
 
    $scope.addItem = function (val) { 
 
     $scope.alertas.push({desc:$scope.addMe}); 
 
    }  
 
    $scope.removeItem = function (x) { 
 
     $scope.alertas.splice(x, 1); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
 

 
<div ng-app="myApp" ng-controller="myCtrl"> 
 
{{alertas}} 
 
    <ul> 
 
    <li ng-repeat="alerta in alertas">{{alerta.desc}} <span ng-click="removeItem($index)">×</span></li> 
 
    </ul> 
 
    <input ng-model="addMe"> 
 
    <button ng-click="addItem()">Add</button> 
 
</div>