如何在angular中为动态创建的复选框定义模型

How to define a model for dynamically created checkboxes in angular

本文关键字:创建 复选框 定义 模型 动态 angular      更新时间:2023-09-26

我正在创建一个用户表,我想在每一行上添加一个复选框和一个删除按钮。当我点击删除按钮时,我想删除所有被选中的用户。

现在我从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为选中复选框的所有用户。

即使我创建了一个对象并将其指定为checkbox的模型,我如何在该对象中添加一个键作为id ?

你可以直接写<input type="checkbox" ng-model="user.isSelected">

然后将MyCntrl.data.users过滤为isSelected === true

由于JavaScript的动态类型特性,没有什么可以阻止您向模型中添加名为'isSelected'(或类似的)的字段。然后,您可以将ng-model="user.isSelected"添加到checkbox标记中。然后,在删除时,检查哪些条目将isSelected设置为true并删除它们。

下面是如何在另一个数组中跟踪所有选定用户的示例:

例子:恰好

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