【问题标题】:AngularJS add value of checkboxes to an arrayAngularJS将复选框的值添加到数组
【发布时间】:2013-06-06 12:20:23
【问题描述】:

我有这个代码:

<tr ng-repeat="doc in providers">      
  <td><input type="checkbox" ng-true-value="{{doc.provider.Id}}" ng-false-value="" ng-model="ids"></td> 
</tr>

{{ids}}

我想获取数组中复选框的值

【问题讨论】:

  • 为什么不将下面的标记为答案

标签: javascript html angularjs angularjs-scope angularjs-ng-repeat


【解决方案1】:

ng-true-value 仅接受字符串,因此您需要使用解决方法。这是feature request 有一段时间了。同时,您可以这样做:

在控制器中创建一个ids 对象,如:

$scope.ids = {};

并更改ng-model 以引用该对象中的键。您可以使用默认的true/false 复选框值:

<td><input type="checkbox" ng-model="ids[doc.provider.Id]"></td>

然后您可以遍历ids 中的键以检查true

Here is a fiddle

【讨论】:

    【解决方案2】:

    我发现this directive 提供了我正在寻找的功能。我在使用更常见的解决方案时遇到的主要问题是我有两个数组,我需要它们来存储与多选列表兼容的数据。 checklistModel 指令提供了这个非常基本的功能并适用于多个模型。

    【讨论】:

      【解决方案3】:

      首先我会说我真的不喜欢在 Angular 中执行此操作的选项。我什至不能说这比公认的答案更好,但它确实将数据保留在模型中。

      标记:

      <tr ng-repeat='(index, doc) in provider'>
          <td><input type='checkbox' ng-true-value='{{doc.provider.Id}}' ng-model='ids[index]' /></td>
      </tr>
      
      <span ng-repeat='id in ids'>{{id}} </span>
      

      现在只需 $watch 数组值并在控制器中更改时进行过滤(确保传递对象相等参数):

      $scope.ids = [];
      
      $scope.updateIds = function() {
          $scope.ids = $scope.ids.filter(function(id) {
              return !!id;
          });
      };
      
      $scope.$watch('ids', $scope.updateIds, true);
      

      当我开始回答这个问题时,我认为最惯用的选项是在输入中添加一个 ng-change 指令:

      <input type='checkbox' ng-true-value='{{doc.provider.Id}}' ng-model='ids[index]' ng-change='updateIds()'/>
      

      不幸的是,这并没有按预期工作。删除值时 UI 无法正确更新。我还想指出,您可以在没有重复指令的情况下执行此操作:

      <input type='checkbox' ng-true-value='1' ng-model='ids.0' />
      <input type='checkbox' ng-true-value='2' ng-model='ids.1' />
      <input type='checkbox' ng-true-value='3' ng-model='ids.2' />
      <input type='checkbox' ng-true-value='4' ng-model='ids.3' />
      <input type='checkbox' ng-true-value='5' ng-model='ids.4' />
      <input type='checkbox' ng-true-value='6' ng-model='ids.5' />
      

      在这种情况下,$watch 肯定比在每个输入中添加 ng-change 更好。最后,这是一个有效的plunkr。每次选中或取消选中一个框时,$watch 函数最终都会运行两次,但这确实是必须的!

      【讨论】:

        猜你喜欢
        • 2015-05-19
        • 2011-11-16
        • 2021-09-24
        • 1970-01-01
        • 2014-01-26
        • 2020-11-03
        • 1970-01-01
        • 2020-09-11
        • 1970-01-01
        相关资源
        最近更新 更多