我正在使用Angular Material,我正在使用复选框进行简单验证。
问题:
至少应选中一个复选框。
1 - 如果我点击一个复选框然后再次点击,则不会显示“必填邮件”。
2 - 如果我点击一个复选框,然后我再次点击,然后按“Tab键”,每个复选框按Tab键,当我到达最后一个并按Tab键时,消息“必需“出现。
我想要的是,条件号1也出现了,还有一件事,我不想在应用程序加载时显示“必需”消息。这是我的例子:https://codepen.io/anon/pen/zrjjyL
我希望你能帮我一臂之力,谢谢!!!!!
代码:
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);
});
答案 0 :(得分:0)
您可以使用formName.$dirty
检查表单是否已被修改。然后,如果表单实际上是脏的,则只能显示错误。
<div ng-message="required" ng-if="myForm.$dirty">Required.</div>
答案 1 :(得分:0)
您正在迭代items
并使用每个新项目覆盖myFrom.permiso
,这意味着myForm.permiso
始终是item
中items
的模型}。这就是为什么,当你选中它们时,只有最后一次更改注册。
您应该删除复选框的name
属性并添加ng-change
处理程序而不是$watch
。
并为permiso
模型添加隐藏的复选框,您可以在更改时更新。