我在角度中遇到父表单失效问题 - 当子表单手动设置为无效时,父表单仍然有效。
这是jsFiddle的简单示例:jsFiddle
<div ng-app="demoApp" ng-controller="exampleController">
Parent Form
<form name="parentForm">
<input type="text" required ng-model="input" name="input"/>
<span ng-if="parentForm.$invalid">NG-INVALID</span>
<span ng-if="parentForm.$valid">NG-VALID</span>
<br>
Nested form
<ng-form name="nestedForm">
<br>
<button type="button" ng-click="setValidity(nestedForm)">Set invalid</button>
<span ng-if="nestedForm.$invalid">NG-INVALID</span>
<span ng-if="nestedForm.$valid">NG-VALID</span>
</ng-form>
</form>
var demoApp = angular.module('demoApp', []);
demoApp.controller('exampleController', function ($scope) {
$scope.setValidity = function(classicNested){
classicNested.$invalid = !classicNested.$invalid;
classicNested.$valid = !classicNested.$valid;
};
});
这是正确的做法吗?我不确定为什么它不起作用......
答案 0 :(得分:0)
这正是FormController具有$setValidity方法的原因。如果有以下内容,它也确保调整父表单的有效性:
$scope.setValidity = function(classicNested) {
classicNested.$setValidity('nested', classicNested.$invalid);
};