AngularJS:有什么方法可以确定哪些字段使表单无效?
在AngularJS应用程序中,在一个控制器内部有下面的代码,它是从一个ng-submit函数调用的,该函数属于名称为profileForm的表单: 
 $scope.updateProfile = function() { if($scope.profileForm.$invalid) { //error handling.. } //etc. }; 
在这个函数里面,有什么办法可以找出哪些字段导致整个被称为无效?
 每个inputname的validation信息在scope以form名称的form公开。 
HTML
 <form name="someForm" action="/"> <input name="username" required /> <input name="password" type="password" required /> </form> 
JS
 $scope.someForm.username.$valid // > false $scope.someForm.password.$error // > { required: true } 
 公开的属性是$pristine , $dirty , $valid , $invalid , $error 。 
如果您想由于某种原因来迭代错误:
 $scope.someForm.$error // > { required: [{$name: "username", $error: true /*...*/}, // {$name: "password", /*..*/}] } 
错误中的每个规则都将暴露在$ error中。
这里是一个plunkr玩http://plnkr.co/edit/zCircDauLfeMcMUSnYaO?p=preview
用于检查哪个表单域无效
 console.log($scope.FORM_NAME.$error.required); 
这将输出窗体的无效字段数组
 你可以通过form.$error.pattern循环form.$error.pattern 。 
 $scope.updateProfile = function() { var error = $scope.profileForm.$error; angular.forEach(error.pattern, function(field){ if(field.$invalid){ var fieldName = field.$name; .... } }); } 
如果您想查看哪些字段与validation混淆,并且您有jQuery来帮助您,只需在javascript控制台上search“ng-invalid”类即可。
 $('.ng-invalid'); 
它会列出所有由于任何原因未通过validation的DOM元素。
 当任何字段是无效的,如果你试图获得它的价值,它将是undefined 。 
 比方说,你有一个文本input附加到$scope.mynum只有当你键入数字,你已经键入了ABC 。 
 如果你试图得到$scope.mynum的值,那将是undefined 。 它不会返回ABC 。 
(也许你知道这一切,但无论如何)
 因此,我将使用一个数组,其中包含所有需要validation的元素,并将其添加到作用域中,并使用filter(例如使用underscore.js)来检查哪些作为typeof undefined返回。 
而那些将是导致无效状态的领域。
我想显示所有的错误,在禁用保存button工具提示,所以用户将知道为什么是禁用,而不是上下滚动长表单。
注意:记住要将名称属性添加到表单中的字段
  if (frm) { disable = frm.$invalid; if (frm.$invalid && frm.$error && frm.$error.required) { frm.$error.required.forEach(function (error) { disableArray.push(error.$name + ' is required'); }); } } if (disableArray.length > 0) { vm.disableMessage = disableArray.toString(); }