2017-02-09 131 views
0
<div class="col-md-2"> 
    <md-button class="md-raised md-primary" ng-click="deleteDiv()">Remove</md-button> 
    </div> 
scope.deleteDiv = function() { 
     alert(scope.itemsToAdd.length); 
     if(scope.itemsToAdd.length > 1) { 
      scope.itemsToAdd.splice(scope.itemsToAdd.length,1) 
     } 
    }; 

嗨,我是AngularJs.的新手。我對刪除動態創建的div有疑問。 itemsToAdd是一個包含四個字段的數組。我使用push和ng-repeat動態添加這些字段。當單擊Remove按鈕時,我得到數組的長度,並且只在大於1時刪除。刪除過程I posted,Is是正確的?其中,我做錯了什麼?.Thanks從angularjs中刪除列表中的最後一個元素

+0

你可以使用array_splice()。 – Mohammed

+0

所以你總是想刪除最後一個?或者你有每個實體的刪除按鈕? – devqon

+0

@Mohammed所以你告訴我試試scope.itemsToAdd_splice()? –

回答

1

您需要傳遞要刪除的元素的索引作爲th的參數e接合功能:

if(scope.itemsToAdd.length > 1) { 
    scope.itemsToAdd.splice(scope.itemsToAdd.length-1,1); //index of the last element is the length of the array minus 1 
} 
+0

非常感謝。它工作:) –

0

通過這個,它的類型之一,你想

<html> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
 
<body ng-app="myApp" ng-controller="todoCtrl"> 
 

 
<h2>My Todo List</h2> 
 

 
<form ng-submit="todoAdd()"> 
 
    <input type="text" ng-model="todoInput" size="50" placeholder="Add New"> 
 
    <input type="submit" value="Add New"> 
 
</form> 
 

 
<br> 
 

 
<div ng-repeat="x in todoList"> 
 
    <input type="checkbox" ng-model="x.done"> <span ng-bind="x.todoText"></span> 
 
</div> 
 

 
<p><button ng-click="remove()">Remove marked</button></p> 
 

 
<script> 
 
var app = angular.module('myApp', []); 
 
app.controller('todoCtrl', function($scope) { 
 
    $scope.todoList = [{todoText:'Clean House', done:false}]; 
 

 
    $scope.todoAdd = function() { 
 
     $scope.todoList.push({todoText:$scope.todoInput, done:false}); 
 
     $scope.todoInput = ""; 
 
    }; 
 

 
    $scope.remove = function() { 
 
     var oldList = $scope.todoList; 
 
     $scope.todoList = []; 
 
     angular.forEach(oldList, function(x) { 
 
      if (!x.done) $scope.todoList.push(x); 
 
     }); 
 
    }; 
 
}); 
 
</script>

+1

考慮解釋你如何解決OP的問題,而不是隻發佈代碼,使您的答案更有用的OP和未來的讀者。 – LionC

0
<tr ng-repeat="person in persons track by $index"> 
     <td>{{person.name}} - # {{person.id}}</td> 
     <td>{{person.description}}</td> 
     <td nowrap=nowrap> 
      <a href="#!/edit"><i class="icon-edit"></i></a> 
      <button ng-click="delete($index)"><i class="icon-minus-sign"></i></button> 
     </td> 
</tr> 

,並在controlelr

$scope.delete=function(index){ 
    $scope.persons.splice(index,1); 
} 
+0

我的按鈕是在ng-repeat之外,所以我不能使用索引變量 –

+0

可以分享complate表我可以找到解決方法 –

相關問題