2016-09-20 23 views
0

我正在創建一個用戶表,其中我想在每一行上添加一個複選框並刪除一個按鈕。當我點擊刪除按鈕時,我想要刪除所有選中的用戶。如何定義角度動態創建的複選框的模型

現在我從API響應中創建這些用戶條目,它給了我說ID,名稱和電子郵件。

所以我的觀點看起來是這樣的:

<tr ng-repeat="user in MyCntrl.data.users track by $index"> 
    <td><input type="checkbox"></td> 
    <td>{{user.name}}</td> 
    <td>{{user.email}}</td> 
</tr> 

我想在我的控制器是有一個對象與所有對他們來說,被點擊複選框用戶的ID。

即使我創建一個對象並將其指定爲複選框的模型,如何在該對象中添加一個作爲id的鍵?

回答

2

你可以簡單地做<input type="checkbox" ng-model="user.isSelected">

然後就是過濾MyCntrl.data.users對於那些有isSelected === true

+0

啊,這是一個愚蠢的問題。我不知道爲什麼我要創建一個新的對象來存儲它,而不是僅僅使用現有的對象。感謝您的快速幫助。 –

1

因爲JavaScript動態類型性質的,沒有什麼可以阻止您添加一個名爲「isSelected」(或類似)到現場你的模型。然後,您可以將ng-model="user.isSelected"添加到您的checkbox標記中。 然後,在刪除時,檢查哪些條目的isSelected設置爲true並刪除它們。

0

這裏有一個如何可以跟蹤所有選定的用戶在另一個數組的例子:

例子:Plunker

<tr ng-repeat="user in MyCntrl.data.users track by $index"> 
    <td><input type="checkbox" ng-model="tempVar" ng-click="toggleSelection($index)"></td> 
    <td>{{user.name}}</td> 
    <td>{{user.email}}</td> 
</tr> 

<!-- AngularJS Code --> 
<script type="text/javascript"> 
var app = angular.module('myApp', []); 

app.controller('MyCtrl', function($scope) { 
    $scope.selectedUsers = []; // initially the selected users array is empty 
    $scope.toggleSelection = function(index){ 
    var positionInSelectedArray; 
    var arr = $scope.MyCntrl.data.users; 
    var tempUser = arr[index]; // refers to the selected user object in $scope.MyCntrl.data.users array (further, we'll call it "arr") 


    var userAlreadySelected = $scope.selectedUsers.filter(function(obj) { 
     return obj.userId == tempUser.userId; 
    })[0]; //checks whether the user is already selected or not (if selected, then returns the user object) 
    if (angular.isUndefined(userAlreadySelected)) { 
     $scope.selectedUsers.push(tempUser); //insert the object in array containing selected users 
    }else{ 
     positionInSelectedArray = $scope.selectedUsers.indexOf(userAlreadySelected); 
     $scope.selectedUsers.splice(positionInSelectedArray, 1); //removes the user object from array containing selected users 
    } 
    }; 
}); 
</script> 
+0

本示例中添加了plunker:https://plnkr.co/edit/P3InnaQv2z4CeojXlusl?p=preview –