I have encountered an issue while using Angular Material for simple validation with checkboxes.
The Challenge :
Requirement: At least one checkbox must be checked.
1- When I click a checkbox and then click again, the "required message" does not appear.
2- After clicking a checkbox, pressing the "Tab key" to navigate through each checkbox results in the "Required" message appearing only when reaching the last checkbox and pressing Tab again.
I am seeking a solution where condition number 1 also triggers as expected. Additionally, I do not want the "required" message to display upon application loading. Here is my example : https://codepen.io/anon/pen/zrjjyL
Your assistance would be greatly appreciated. Thank you!
Code :
HTML:
<form name="myForm" ng-app="myApp" ng-controller="myController"
class="container-fluid" ng-submit="submit()">
<div class="row">
<div class="col-xs-8">
<md-input-container md-no-float>
<label>Name *</label>
<input required="" name="nombre" ng-model="model.nombre">
<div ng-messages="myForm.nombre.$error" ng-
show="myForm.nombre.$touched || myForm.$submitted">
<div ng-message="required">Required.</div>
</div>
</md-input-container>
<md-input-container md-no-float>
<label>Search Options *</label>
<input type="text" id="query" ng-model="query"/>
</md-input-container>
<md-input-container md-no-float>
<md-list-item ng-repeat="item in items | filter:query">
<p style ="font-size: 1.3rem;font-family: Roboto,'Helvetica
Neue',sans-serif"> {{ item.title }} </p>
<md-checkbox name ="permiso" ng-
model="model.opciones[item.id]['checked']" ng-required="!isChecked" ></md-
checkbox>
</md-list-item>
<div ng-messages="myForm.permiso.$error" ng-show=" myForm.permiso.$touched
|| myForm.$submitted">
<div ng-message="required">Required.</div>
</md-input-container>
</div> </div>
JS:
var app = angular.module('myApp', ['ngAnimate', 'ngAria', 'ngMaterial',
'ngMessages'])
.controller('myController', function($scope) {
$scope.items = [{
id: 1,
title: 'Item A'
}, {
id: 2,
title: 'Item A'
}, {
id: 3,
title: 'Item C'
}];;
$scope.model = {}
$scope.model.opciones = {};
$scope.isChecked = false;
$scope.$watch('model.opciones', function(selected) {
$scope.isChecked = false;
angular.forEach(selected, function(selectedItem) {
if (selectedItem.checked) $scope.isChecked = true;
});
}, true);
});