Watch form validity from controller

六月ゝ 毕业季﹏ 提交于 2019-12-13 02:26:03

问题


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...)


回答1:


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?



来源:https://stackoverflow.com/questions/25027876/watch-form-validity-from-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!