lundi 21 août 2017

AngularJS - How to submit an array of checkbox selections dynamically

I'm building a really simple form with angular. I have an array of objects, like this:

data: [{id: 1, name: "Peter"},{id: 2, name: "Paul"}...]

And I need to build some checkboxes off of that data. A user can select multiple values. Then, when they hit submit, I should send an array of id numbers off to the DB, formatted like this:

{nameIds: [1,2]}

And I'm having a hell of a time building that array. I've been following other S.O. examples, but something isn't clicking. This is what I have right now:

    <label ng-repeat="name in vm.nameArray">
            <input type="checkbox" ng-model="name.selected"> 
    </label>
        <button ng-click="vm.submit()" class="btn btn-primary margin-10-tb">NEXT</button>

and in my controller:

vm.nameArray = response.data.data;
vm.selectedNames = [];
vm.nameIds = [];
vm.submit = function() {
  vm.selectedNames = vm.nameArray.filter(function(name){
    if (name.selected) return name.id;
  });
  vm.selectedNames.forEach(function(name){
    vm.nameIds.push(name.id);
  });
};

Maybe you've already guessed, but the issue here is that when a user deselects a name they've previously added, vm.nameIds does not update. The id for the deselected name persists in the array.

Any tips on how to best create this dynamic array for submission would be much appreciated.




Aucun commentaire:

Enregistrer un commentaire