I am building a dynamic form that could include any number of field combinations and field types. A typical example of this might be a user registration with firstName, lastName, email and password. However also to be included on some forms would be a boolean checkbox for a field like active.
I have an empty object in my controller that will be populated by the form and then submitted. I attach ng-modelto all of the form elements as usual, these all work well until I get to the boolean field which does not get included in the model unless the user has interacted with it.
The boolean field is usually required at the server side so I want it to be checked by default, but this won't be added to the model unless you first uncheck it and check it again.
$scope.formData = {}
<div class="{{field.name}}">
<label for={{field.name}} class="field-label">{{field.prettyName}}</label>
<input
type="checkbox"
class="form-field boolean-checkbox"
id={{field.name}}
ng-model="formData[field.name]"
ng-checked="true"
/>
</div>
So the scenarios are:
Initial page load checkbox is checked but object reads as:
{}
The user then has to uncheck the checkbox, and then recheck it and the object will read as:
{
"active":true
}
I have also tried using ng-init="true" but no joy there.
formData[field.name]does not exist so it is going to be false. You could run it through a function and set it to true if it does not exist yet.