2016-01-28 52 views
1

我正在使用Angular Material,我正在用复选框进行简单验证。Angular JS/Angular Material。如何验证点击复选框组?

问题:

至少一个复选框应进行检查。

- 如果我点击一个复选框,然后再次单击,则不会显示“所需消息”。如果我点击一个复选框,然后再次点击,然后按Tab键,每个复选框按Tab键,当我到达最后一个并按Tab键时,出现消息“必需”。

我想要的是,条件编号1也出现了,和另外一件事,我不想在应用程序加载时显示“required”消息。这里是我的例子: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

可以检查的形式进行了修改与formName.$dirty。然后,如果表单实际上很脏,则只能显示错误。

<div ng-message="required" ng-if="myForm.$dirty">Required.</div>

+0

嗨感谢您的回答,但它并没有在这里工作是CodePen与您建议的更改:HTTPS://codepen.io/anon/pen/JGZRWp 再次感谢! –

0

你迭代的items,并与每一个新的项目,这意味着myForm.permiso覆盖myFrom.permiso总是最后item在你items模型。这就是为什么当你选中它们时,只有最后一个更改寄存器。

您应该删除复选框的name属性,并添加ng-change处理程序而不是$watch。 然后您为permiso型号添加一个隐藏复选框,您在更改时更新。 !

https://codepen.io/kuhnroyal/pen/LGrzGv