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 

尝试这个

鉴于:

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

在控制器中:

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

要么

鉴于:

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

在控制器中:

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

我已经更新了控制器:

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

这是另一个解决scheme

在你的html中设置一个隐藏的范围variables,然后你可以从你的控制器中使用它:

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

这是一个完整的工作例子:

 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:hidden" >{{ formValid = myForm.$valid}}</span> <br/> <button ng-click="isFormValid()">Check Valid</button> </form> </body> </html> 

BusinessCtrlcreateBusinessFormFormController之前被初始化。 即使你的ngController上的ngController不能按你想要的方式工作。 你不能这样做(你可以创build你的ngControllerDirective ,并试图欺骗优先级。)这是angularjs如何工作。

看到这个plnkr例如: http ://plnkr.co/edit/WYyu3raWQHkJ7XQzpDtY?p=preview