我想检查一个表单在角度控制器中是否有效。使用 $scope 时这似乎很简单,但我无法让它与“控制器作为”语法一起使用。
当我尝试访问 form.$valid 时,我收到错误消息"Cannot read property '$valid' of undefined"。
plunkr:http ://plnkr.co/edit/w54i1bZVD8UMhxB4L2JX?p=preview
HTML
<div ng-app="demoControllerAs" ng-controller="MainController as main">
<form name="contactForm" novalidate>
<p>
<label>Email</label>
<input type="email" name="email" ng-model="main.email" required />
</p>
<p>
<label>Message</label>
<textarea name="message" ng-model="main.message" required></textarea>
</p>
<input type="submit" value="submit" ng-click="main.submit()" />
</form>
</div>
JS
var app = angular.module('demoControllerAs', []);
app.controller('MainController', [function () {
var main = this;
main.submit = function () {
var isValid = main.contactForm.$valid;
console.log(isValid);
};
}]);