AngularJS将复选框的值添加到数组中

问题描述 投票:18回答:3

我有此代码:

<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
3个回答
25
投票

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


7
投票

我发现this directive提供了我想要的功能。使用更常见的解决方案时遇到的主要问题是,我需要两个数组来存储与多选择列表兼容的数据。 checklistModel指令提供了非常基本的功能,并且可以与多个模型一起使用。


5
投票

首先,我真的不喜欢这种选择。我什至不能说这比公认的答案要好,但是它确实将数据保留在模型中。

标记:

<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函数的确会在每次选中或未选中某个框时运行两次,但这确实是必须的!

© www.soinside.com 2019 - 2024. All rights reserved.