【问题标题】:add and obtain data of ngRepeat of checkboxes添加和获取复选框的ngRepeat数据
【发布时间】:2017-08-23 06:10:25
【问题描述】:

好吧,我有一个问题,我有一个 ng-repeat 显示当前的用户,我每天都必须添加用户的饭菜,这就是为什么我有 5 个复选框,3 个必须标记而 2 个没有,当准备好的用户添加这些膳食数据时出现问题,但我没有收到来自复选框的任何数据。

我需要立即将这些复选框的值添加到我在函数中收到的数据中。

<tr ng-repeat="users in usersData">
    <td>
        {{ $index + 1 }}
    </td>
    <td>
        {{ users.id }}
    </td>
    <td>
        {{ users.apellidos }}
    </td>
    <td>
        {{ users.nombres }}
    </td>
    <td>
        <input class="form-control" type="checkbox" style="width: 100px;" ng-model="users.desayuno" ng-checked="true">
    </td>
    <td>
        <input class="form-control" type="checkbox" style="width: 100px;" ng-model="users.almuerzo" ng-checked="true">
    </td>
    <td>
        <input class="form-control" type="checkbox"  style="width: 100px;" ng-model="users.te" ng-checked="true">
    </td>
    <td>
        <input class="form-control" type="checkbox" style="width: 100px;" ng-model="users.cena">
    </td>
    <td>
        <input class="form-control" type="checkbox" style="width: 100px;" ng-model="users.amanecida">
    </td>
</tr>

这里没有显示 users.desayuno users.almuerzo users.te users.cena users.amanecida

$scope.saveDataDining = function() {
    angular.forEach($scope.usersData, function(obj) {
      console.log(obj);
    });
  };

这里有一个问题。

https://plnkr.co/edit/tHNhKQObkjRtUEfmI19o?p=preview

【问题讨论】:

  • 从未一起使用过ng-checkedng-model 指令,reference here.. 只需使用ng-checked 将复选框值设为真,就不会更新ng-model 值。相反,您应该通过循环遍历每个元素将那些需要的标志显式设置为 true..
  • 很好尝试不同的方式,我最终使用了“ng-checked”,但即便如此,我也没有得到复选框的值,也没有使用“ng-checked”
  • 在绑定数据之前,您可以像angular.forEach($scope.usersData, function(obj) { angular.extend(obj, {desayuno: true,almuerzo: true, te: true }); });一样轻松将每个元素标志设置为true
  • 这项工作,谢谢。
  • documentation for ng-checked 明确指出:请注意,该指令(ng-checked)不应与ngModel 一起使用,因为这可能会导致意外行为。

标签: javascript angularjs checkbox


【解决方案1】:

正如@georgeawg 所说:

ng-checked 的documentation 明确指出:请注意,此指令 (ng-checked) 不应与 ngModel 一起使用,因为这可能导致意外行为。

  1. 改为初始化控制器中的对象

    $scope.usersData = [{
      id: 1,
      nombres: "Amilkar Shegrid",
      apellidos: "Contreras Castro",
      sexo: "MASCULINO",
      codido_seguro: 5213635,
      desayuno: true,
      almuerzo: true,
      te: true,
      cena: false,
      amanecida: false
    }, {...
    
  2. 并在复选框中添加ng-changeng-click 函数以设置值

    // controller
    $scope.toggleDesayuno = function(userid) {
      var u = $scope.usersData.find((user)=>userid==user.id)
      u.desayuno = !u.desayuno
    }
    
    // template
    <input class="form-control" type="checkbox" style="width: 100px;" ng-click="toggleDesayuno(users.id)">
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多