Cocorico
Cocorico

Reputation: 2347

Dynamically create angular checkboxes and get their values

I have a program that needs to check an API for all the current users on the system, and then present a form to an administrator who can decide which ones to give certain powers. I can't figure out how to get the information modeled into my formData in order to do this. I have this but it does not work:

<p ng-repeat="f in mdfields"><input type="checkbox" ng-model="formData.checkboxes" ng-true-value="{{f}}"> {{f}}</p>

The mdfields is just an array of every user's name.

That may give you an idea though of what I want: I just want to display all the names of users, and let the admin select as many of them as he wants, then have that information available to $scope.formData so I can pass it to another API call and do stuff.

Edit: To clarify a bit, the list of checkboxes that gets called can change often, and ideally, I want the ability to send some data back to the server that says specifically something like: ["jao smith":true] ["frank jones":false]

although it would be fine to send back to server only the names of people who have been checked.

Upvotes: 0

Views: 1894

Answers (1)

charlietfl
charlietfl

Reputation: 171679

Without knowing more about you models there are several ways you can do it:

As property of fobject - can filter mdfields array to find selected:

<input ng-model="f.selected">

All in one scope variable array (not a good choice if doing any filtering because indexing changes):

<input  ng-model="formData.checkboxes[$index]"
        ng-init="formData.checkboxes[$index]=formData.checkboxes[$index]|false">

In a scope variable object - easy to collect selected by id

<input  ng-model="formData.checkboxes[f.id]">

Upvotes: 1

Related Questions