控制器的监视表格有效性 [英] Watch form validity from controller

查看:62
本文介绍了控制器的监视表格有效性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有一个表格.我希望能够根据此表单的有效性设置作用域变量.我已经给表格起了一个名字:

I have a form within my controller. I'd like to be able to set a scope variable based on the validity of this form. I've given the form a name already:

<div ng-controller="myCtrl">

    ...

    <form name='myForm'>
        ...
    </form>

    ...

</div>

并已在该表单的$ valid属性(位于包含此表单的控制器中)上创建了一个$ watch:

And have created a $watch on that form's $valid property (this is located in the controller which contains this form):

$scope.$watch('myForm.$valid', function(oldVal, newVal) {
    console.log("Woo! This might be working!");
    if (newVal) {
        $scope.otherVar = true;
    } else {
        $scope.otherVar = false;
    }
}

我的日志语句仅在页面加载时显示,但在表单的有效性更改时则不显示. (我已通过插入验证表单的$ valid属性是否正在更改:

{{myForm.$ valid}}

My log statement ONLY appears on page load, but not when the form's validity changes. (I've verified that the form's $valid property is changing by inserting:

{{ myForm.$valid }}

我一直在寻找SO,从我看到的这个应该开始. (虽然显然有问题...)

I've been looking around SO and from what I've seen this should be working. (Obviously something is wrong though...)

推荐答案

我认为您的问题是function(oldVal, newVal)应该是function(newVal, oldVal). 除此之外,我在您的代码中找不到任何错误. 这是一个工作正常的plunkr示例: http://plnkr.co/edit/ur42HFcVQbpTEBkRBtdY?p=preview

I think your problem is function(oldVal, newVal) should be function(newVal, oldVal). Apart from that I can't find any fault in your code. Here's a working plunkr example: http://plnkr.co/edit/ur42HFcVQbpTEBkRBtdY?p=preview

除此之外,代码中可能还存在其他影响表单的内容,您没有将其嵌套在ng-ifng-view之类的东西中吗?

Outside of that it's probably something else in your code affecting the form, you don't have it nested in something like an ng-if or ng-view?

这篇关于控制器的监视表格有效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆