从控制器观察表单有效性 [英] Watch form validity from controller

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

问题描述

我的控制器中有一个表单.我希望能够根据此表单的有效性设置范围变量.我已经为表单命名了:

...<表单名称='myForm'>...</表单>...

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

$scope.$watch('myForm.$valid', function(oldVal, newVal) {console.log("哇!这可能有用!");如果(新值){$scope.otherVar = true;} 别的 {$scope.otherVar = false;}}

我的日志语句只出现在页面加载时,但不会在表单的有效性改变时出现.(我已经通过插入验证表单的 $valid 属性正在更改:

{{ myForm.$valid }}

在我的表格范围内)

我一直在环顾四周,从我看到的情况来看,这应该是有效的.(虽然显然有些不对劲……)

解决方案

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

除此之外,它可能是您的代码中影响表单的其他东西,您没有将它嵌套在诸如 ng-ifng-view 之类的东西中?

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>

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;
    }
}

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 }}

within the scope of my form)

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

解决方案

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

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天全站免登陆