How to get an Array with just the values from selected checkboxes?

前端 未结 2 1875
醉酒成梦
醉酒成梦 2021-01-26 04:37

How can I bind checkboxes to an array in my model, so that the array always contains just the values corresponding to the selected checkboxes?

For example, instead of:

2条回答
  •  无人及你
    2021-01-26 05:42

    There is no native support in AngularJS for checkboxes adding/removing values from an array. There cannot be, because form control model-view binding is managed by ngModel, which requires the control (input) to bind its value to a separate assignable expression (so there's no way to make ngModel delete a value when the checkbox is unchecked).

    Don't Mind undefined

    You can either solve this by making model.groups an Array and using doing the following code:

    
    

    and then filter out the undefineds when using the array.

    Computed Property

    Or you can just assign the boolean true/false values to an object and set a $watch on that object that automatically updates your array.

    
    

    +

    var groups = $scope.model.groups = [];
    $scope.$watch('model.groupFlags', function (flags) {
        groups.length = 0;
        for (var key in flags) {
            groups.push(key);
        }
    }, true);
    

    Original answer (the question was unclear):

    The documentation suggests that ng-true-value and ng-false-value should work just fine:

    
    

提交回复
热议问题