AngularJS 检查表单是否在控制器中有效

我需要检查表单在控制器中是否有效。

观看内容:

<form novalidate=""
name="createBusinessForm"
ng-submit="setBusinessInformation()"
class="css-form">
<!-- fields -->
</form>

在我的控制器里:

.controller(
'BusinessCtrl',
function ($scope, $http, $location, Business, BusinessService,
UserService, Photo)
{


if ($scope.createBusinessForm.$valid) {
$scope.informationStatus = true;
}


...

我得到了这个错误:

TypeError: Cannot read property '$valid' of undefined
118316 次浏览

I have updated the controller to:

.controller('BusinessCtrl',
function ($scope, $http, $location, Business, BusinessService, UserService, Photo) {
$scope.$watch('createBusinessForm.$valid', function(newVal) {
//$scope.valid = newVal;
$scope.informationStatus = true;
});
...

The BusinessCtrl is initialised before the createBusinessForm's FormController. Even if you have the ngController on the form won't work the way you wanted. You can't help this (you can create your ngControllerDirective, and try to trick the priority.) this is how angularjs works.

See this plnkr for example: http://plnkr.co/edit/WYyu3raWQHkJ7XQzpDtY?p=preview

Try this

in view:

<form name="formName" ng-submit="submitForm(formName)">
<!-- fields -->
</form>

in controller:

$scope.submitForm = function(form){
if(form.$valid) {
// Code here if valid
}
};

or

in view:

<form name="formName" ng-submit="submitForm(formName.$valid)">
<!-- fields -->
</form>

in controller:

$scope.submitForm = function(formValid){
if(formValid) {
// Code here if valid
}
};

Here is another solution

Set a hidden scope variable in your html then you can use it from your controller:

<span style="display:none" >\{\{ formValid = myForm.$valid}}</span>

Here is the full working example:

angular.module('App', [])
.controller('myController', function($scope) {
$scope.userType = 'guest';
$scope.formValid = false;
console.info('Ctrl init, no form.');
  

$scope.$watch('myForm', function() {
console.info('myForm watch');
console.log($scope.formValid);
});
  

$scope.isFormValid = function() {
//test the new scope variable
console.log('form valid?: ', $scope.formValid);
};
});
<!doctype html>
<html ng-app="App">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
</head>
<body>


<form name="myForm" ng-controller="myController">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
<tt>userType = \{\{userType}}</tt><br>
<tt>myForm.input.$valid = \{\{myForm.input.$valid}}</tt><br>
<tt>myForm.input.$error = \{\{myForm.input.$error}}</tt><br>
<tt>myForm.$valid = \{\{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = \{\{!!myForm.$error.required}}</tt><br>
  

  

/*-- Hidden Variable formValid to use in your controller --*/
<span style="display:none" >\{\{ formValid = myForm.$valid}}</span>
  

  

<br/>
<button ng-click="isFormValid()">Check Valid</button>
</form>
</body>
</html>