问题描述
我的控制器中有一个表单.我希望能够根据此表单的有效性设置范围变量.我已经为表单命名了:
...<表单名称='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-if
或 ng-view
之类的东西中?
<div ng-controller="myCtrl">
...
<form name='myForm'>
...
</form>
...
</div>
$scope.$watch('myForm.$valid', function(oldVal, newVal) {
console.log("Woo! This might be working!");
if (newVal) {
$scope.otherVar = true;
} else {
$scope.otherVar = false;
}
}
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
?
这篇关于从控制器观察表单有效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!