2016-02-02 29 views
0

我有一個簡單的3個項目的渲染,其特定的ID與那裏的名稱字段粘在一起。每當我只用按鈕來刪除該行時,我想顯示一條特定消息。當我這樣做的時候,我只是在傳遞該特定行的id時出現問題,並且所有n行(這裏是3)都被刪除了。AngularJs - ngRepeat在視圖中刪除特定的行

HTML:

<html> 
<head> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script> 

</head> 
<body ng-app="myApp" ng-controller="myCtrl"> 
<div> 
    <p ng-repeat="x in List" ng-show="!deleted">{{x.name}}<button ng-click="del(x.id)">Delete</button></p> 
    <p ng-show="deleted">This line has been deleted.</p> 
</div> 

<script> 
//module declaration 
var app = angular.module('myApp',[]); 

//Controller declaration 
app.controller('myCtrl',function($scope){ 
    $scope.deleted = false; 
    $scope.List = [{"name":"Peter Martin","id":"1"},{"name":"Lita Schedan","id":"2"},{"name":"Jenni Markints","id":"3"}]; 
    $scope.del = function(id){ 
     //for this id -> only 
     $scope.deleted = true; 
    } 
}); 

</script> 
</body> 
</html> 

這意味着,如果我把刪除線2的按鈕,第一和第二行必須配備刪除按鈕,但在中間線消息「此行已被刪除「必須顯示。

+0

你必須使用'.slice(1)'' –

回答

1

你應該基本上使用角度過濾器顯示刪除了flag錯誤的行。爲此,您需要確保您的List對象顯示在初始加載時有deleted道具到false。然後點擊傳遞整行對象到del方法。而對於顯示錯誤信息,您可以使用$timeout,將顯示一個消息半秒

標記

<div> 
    <p ng-repeat="x in List | filter : {deleted: false}"> 
     {{x.name}} 
     <button ng-click="del(x)">Delete</button> 
    </p> 
    <p ng-show="deleted">Line with id {{deletedId}} has been deleted.</p> 
</div> 

和元素上的點擊做出刪除標誌true

控制器

//Controller declaration 
app.controller('myCtrl',function($scope, $timeout){ 
    $scope.deleted = false; 
    $scope.List = [{"name":"Peter Martin","id":"1"},{"name":"Lita Schedan","id":"2"},{"name":"Jenni Markints","id":"3"}]; 
    angular.forEach($scope.List, function(ele){ 
     ele.deleted = false; 
    }) 
    $scope.del = function(x){ //passed object 
     x.deleted = true; 
     //for showing message 
     $scope.deleted = true; 
     $scope.deletedId = x.id; 
     $timeout(function(){ 
      $scope.deleted = false; 
      $scope.deletedId = undefined; 
     }, 500) 
    } 
}); 

如果你真的想從數組中刪除元素,你可以使用.slice()方法,將$index傳遞給它