大佬教程收集整理的这篇文章主要介绍了AngularJS具有ng-repeat验证的多种形式,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
<div ng-form="form"> <div ng-repeat="field in fields"> <div ng-form="subform"><input...></div> </div> </div>
并验证如下:
if ($scope.form.subform.$invalid && !$scope.form.subform.$error.required) { // Do something... }
(这是非常简化的示例,我有不同输入类型和不同名称的更多不同子表单,例如input [text]被命名为TextForm,input [numeric]是NumericForm等.)
如果只有现场,一切都按预期工作.但是,如果ng-repeat生成多个字段,则验证仅触发最后一个子表单,其他子表单将被忽略.
有没有办法循环遍历所有子表单,以检查其中一个是否无效?
此外,我正在标记所有未填写的必填字段,如下所示:
if ($scope.form.$error.required) { angular.forEach($scope.form.$error.required,function (object,indeX) { $scope.form.$error.required[index].$setDirty(); } ); }
所以,如果我的字段是这样完成的:
....ng-form="TextForm" ng-class="{ 'has-error': TextForm.$dirty && TextForm.$invalid }"....
下面是一个可能的实现来获取每个subForm的错误.
DEMO
JAVASCRIPT(指令)
.directive('ngModelError',function($parse,$timeout) { return { require: ['ngModel','form'],link: function(scope,elem,attr,ctrls) { var ngModel = ctrls[0],ngForm = ctrls[1],fieldGet = $parse(attr.ngModelError),fieldSet = fieldGet.assign,field = fieldGet(scopE); $timeout(function() { field.$error = ngModel.$error; field.ngForm = ngForm; fieldSet(scope,field); }); } }; });
HTML
<form name="form" ng-submit="submit(form,fields)" novalidate> <div ng-form="subForm" ng-repeat="field in fields" ng-class="{'has-error': subForm.$invalid && form.$dirty}"> <label class="control-label">{{field.label}}</label> <input type="{{field.typE}}" placeholder="{{field.placeholder}}" ng-model="field.model" name="field" ng-required="field.isrequired" class="form-control" ng-model-error="field" /> </div> <br> <button type="submit" class="btn btn-priMary">Submit</button> </form>
JAVASCRIPT(控制器)
请注意字段的结构:
.controller('Ctrl',function($scopE) { $scope.fields = { email: { type: 'email',placeholder: 'Enter email',isrequired: true,label: 'Email Address' },password: { type: 'password',placeholder: 'Enter password',label: 'password' } }; $scope.submit = function(form,fields) { form.$dirty = true; if(form.$valid) { // do whatever } else { // accessing ngForm for email field console.log(fields.email.ngForm); // accessing errors for email field console.log(fields.email.$error); // accessing ngForm for password field console.log(fields.password.ngForm); // accessing errors for password field console.log(fields.password.$error); } }; })
以上是大佬教程为你收集整理的AngularJS具有ng-repeat验证的多种形式全部内容,希望文章能够帮你解决AngularJS具有ng-repeat验证的多种形式所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。