AngularJS'controller as'和form.$ valid [英] AngularJS 'controller as' and form.$valid
本文介绍了AngularJS'controller as'和form.$ valid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检查角度控制器内的表单是否有效.使用$ scope时,这似乎很简单,但是我无法使其与"controller as"语法一起使用.
I want to check if a form is valid inside an angular controller. This seems straightforward when using $scope, but I can't get it to work with the 'controller as' syntax.
当我尝试访问form.$ valid时,出现错误消息无法读取未定义的属性'$ valid'" .
When I attempt to access form.$valid I get the error message "Cannot read property '$valid' of undefined".
plunkr: http://plnkr.co/edit/w54i1bZVD8UMhxB4L2JX?p=预览
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);
};
}]);
推荐答案
您可以按照@ ons-jjss的建议进行操作,但是如果您不想将$scope
注入到控制器中,则只需将form
名称更改为
You could do as @ons-jjss suggested but if you prefer not to inject $scope
into you controller, then just change your form
name as
<form name="main.contactForm" novalidate>
它会像魅力一样工作.
这篇关于AngularJS'controller as'和form.$ valid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文