【问题标题】:AngularJS checkboxes for array of numbers [duplicate]数字数组的AngularJS复选框[重复]
【发布时间】:2014-12-17 05:29:16
【问题描述】:

我有一个数字数组,我想将它们显示为用户可以选中/取消选中的复选框选择,然后我想做的是创建另一个值数组表示选中的复选框。

因此,例如,我的选择是:

$scope.options = [500, 1250, 2500, 5000, 10000, 25000, 50000, 100000];

我的第二个数组是:

$scope.selected = [1250, 2500, 5000, 10000, 25000];

我想构建一个看起来像这样的表单:

[ ] 500
[x] 1250
[x] 2500
[x] 5000
[x] 10000
[x] 25000
[ ] 50000
[ ] 100000

并根据表单中选中/未选中的值更新第二个数组。我想我知道如何在第一个数组上使用 ngRepeat 构建表单,并且为复选框设置选中标志应该很简单,但我不确定如何更新第二个数组。

有没有比较简单的方法?

非常感谢任何帮助!谢谢,

迪伦

【问题讨论】:

    标签: javascript arrays angularjs


    【解决方案1】:

    为了与 Angular 中的复选框交互,我建议使用以下指令:http://vitalets.github.io/checklist-model/

    如果你不想使用这个指令,你可以在你指定的 checkboxes 数组上创建观察者。

    例如:

    function MyCtrl($scope) {
        $scope.items = [
            {
                checked: false,
                value: 1
            },
            {
                checked: false,
                value: 2
            },
                    {
                checked: false,
                value: 3
            },
            {
                checked: false,
                value: 4
            }
        ];
    
        $scope.selectedItems = [];
    
        $scope.$watch('items', function(newValues){
            $scope.selectedItems.length = 0;
            angular.forEach(newValues, function(item) {
                if (item.checked == true) {
                    $scope.selectedItems.push(item.value);
                }
            });
        }, true);
    }
    

    你的看法:

    <div ng-controller="MyCtrl">
        <div ng-repeat="item in items">
            <input type="checkbox" ng-model="item.checked"/>          
            {{item.value}}
        </div>
        <pre>{{selectedItems}}</pre>
    </div>
    

    这种方式将允许您始终拥有有关所选复选框的实际信息。

    我已经为您创建了 JSFiddle 和工作示例。

    【讨论】:

    • 更好的是,忘记第二个数组,只依赖items 中的checked 值。没有充分的理由重复数据。
    • @Blazemonger,是的,你是对的,但作者已经写过,他想获得两个数组。通常在与复选框交互的情况下,我建议使用此指令:vitalets.github.io/checklist-model
    • 你应该看看这个指令here
    猜你喜欢
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2015-04-20
    • 2013-11-07
    相关资源
    最近更新 更多