1

I’ve got an array of numbers that I’d like to display as a selection of check boxes that the user can then check/uncheck, and what I’d like to do is to then have another array of values created that represent the checked check boxes.

So, for example, my options are:

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

My second array is:

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

I’d like to build a form that looks something like:

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

And have the second array update depending on the values that are checked/unchecked in the form. I think I know how to get the form built by using ngRepeat on the first array, and setting the checked flag for the check boxes should be simple enough, but what I’m not sure on is how to get the second array updated.

Is there a relatively simple way of doing this?

Any help is greatly appreciated! Thanks,

Dylan

Dylan Parry
  • 3,373
  • 6
  • 26
  • 38

1 Answers1

1

For interaction with ckeckboxes in Angular I recommend to use the following directive: http://vitalets.github.io/checklist-model/

If you don't want to use this directive, you can create watcher on your specified checkboxes array.

For example:

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);
}

Your view:

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

This way will allow you to always have the actual information about the selected checkbox.

I've created JSFiddle with working example for you.

Artyom Pranovich
  • 6,814
  • 8
  • 41
  • 60
  • Better yet, forget the second array and just rely on the `checked` values in `items`. No good reason to duplicate data. – Blazemonger Oct 21 '14 at 21:07
  • @Blazemonger, yeah, you are right but author have written, that he want to get two arrays. And in general in cases of interaction with checkboxes, I suggest to use this directive: http://vitalets.github.io/checklist-model/ – Artyom Pranovich Oct 21 '14 at 21:10
  • You should check out this directive [here](http://stackoverflow.com/a/38213658/4850220) – Vikas Gautam Jul 06 '16 at 18:10