我想检查一个角度控制器内的表格是否有效.使用$scope时这似乎很简单,但是我无法使用’controller as’语法.
当我尝试访问表单时.$valid我收到错误消息“无法读取属性’$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); }; }]);
您可以像@ ons-jjss建议的那样做,但如果您不想将$scope注入您的控制器,那么只需将您的表单名称更改为
<form name="main.contactForm" novalidate>
它会像魅力一样工作.