[英]AngularJS form validity within controller
From what I know, the $valid property (and other similar ones) are accessible with $scope.formname.inputname.$valid from the controller.. 据我所知,$ valid属性(以及其他类似属性)可通过控制器的$ scope.formname.inputname。$ valid访问。
I've played around with this: http://plnkr.co/edit/oEfdMpI3URooJhRFfSUr?p=preview 我玩过这个游戏: http : //plnkr.co/edit/oEfdMpI3URooJhRFfSUr?p=preview
this.validity = $scope.myForm.input.$valid; //ADDED THIS LINE
Why does this one line that I added in script.js break it? 为什么我在script.js中添加的这一行会中断它? I would expect {{ctrl.validity}} to show up as true.
我希望{{ctrl.validity}}会显示为true。
You added that line in a controller's constructor. 您将该行添加到了控制器的构造函数中。
By the time that the constructor instance is created, the form in a view hasn't been compiled yet. 到构造函数实例创建时,视图中的表单尚未编译。
Try using $timeout
to defer the execution of the line like this to make it works: 尝试使用
$timeout
延迟执行该行,以使其起作用:
var ctrl = this;
$timeout(function () {
ctrl.validity = $scope.myForm.input.$valid; //ADDED THIS LINE
});
Or if you want to keep them in sync, use $watch
: 或者,如果您想使其保持同步,请使用
$watch
:
$scope.$watch('myForm.input.$valid', function (isValid) {
ctrl.validity = isValid;
});
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.