I have a form myForm
with some input fields.
What am I trying to implement: Each field is required
only if at least one of the others input fields is not empty.
How I do it: I set ng-required="ctrl.isAtLeasOneFieldSet()"
on each field. This function check to see if any field is set.
Until here it works. If I set a field it returns true
and if no field is set it returns false
. I see it also in the "developer-console-inspector" in Firefox, required changes between true and false when I set and unset a value in one of the input fields.
What doesn't works: I habe a submit function in my controller:
function submitForm(valid) {
if(!valid) {
return;
}
}
And on the form ng-submit="ctrl.submitForm(ctrl.myForm.$valid)"
.
Even though the ng-required
is set to true
and the input field is not set, the valid
in submitForm
returns true
.
I have used this technique thousand times with ng-required="someValue"
but not with a functionl like now and it works fine. I think there is a problem when I set ng-required
with ctrl.isAtLeasOneFieldSet()
. It looks as the form will not get the update to required
.
Here a simulation:
index.html - form
<form name="ctrl.myForm" class="form-horizontal" role="form" data-ng-submit="ctrl.submitForm(ctrl.myForm.$valid)" novalidate>
<input name="name"
data-ng-model="data.name"
data-ng-required="{{ctrl.isAtLeasOneFieldSet()}}"
/>
<input name="surname"
data-ng-model="data.surname"
data-ng-required="{{ctrl.isAtLeasOneFieldSet()}}"
/>
<!---->
</form>
index.js - submitForm()
function submitForm(valid) {
if(!valid) {
return;
}
// Do something else
}