I'm currently experiencing a challenge with checkboxes in my Angular project. Due to the requirements of the backend, each checkbox must have a unique name, but at least one of them needs to be checked before the form can be submitted.
To address this issue, I created a simple directive with the following code:
{
restrict: 'A',
require: ['ngModel', '^form'],
link: function(scope, el, attrs, controllers) {
var ngModel = controllers[0];
var formController = controllers[1];
scope[attrs.validateOneSelected] =
scope[attrs.validateOneSelected] || 0;
ngModel.$validators.oneSelected = function(modelValue, viewValue) {
if (!viewValue && scope[attrs.validateOneSelected] > 0) {
scope[attrs.validateOneSelected]--;
}
else if (viewValue) {
scope[attrs.validateOneSelected]++;
}
return scope[attrs.validateOneSelected] > 0;
};
}
}
This directive maintains a count of checked checkboxes. It increments when a checkbox is checked and decrements when it is unchecked. The form is considered valid only if more than one checkbox is checked.
While this system works well, I encountered an issue where the validators are triggered only when the model value changes, leaving other checkboxes tagged as invalid.
To address this concern, I thought about using a setTimeout
function that would iterate through each $errors.oneSelected
and call $validate
after validation. However, this approach seems cumbersome to me, and I believe there may be a simpler way to solve this problem.
Edit
Feel free to use this Plunker link to experiment with the solution