简体   繁体   English

在angularjs控制器中获取表单验证状态

[英]Getting form validation state inside angularjs controller

I am able to validate my form element 'name'd 'username'. 我能够验证表单元素“名称”为“用户名”。

ng-class="{ 'has-error': form.username.$dirty && form.username.$invalid }"

But I cannot get this info inside a controller. 但是我无法在控制器中获取此信息。 Is this possible? 这可能吗?

I want to do something like this: 我想做这样的事情:

mycontroller.controller('mycontroller', function ($scope){

    $scope.isusernameinvalid = $scope.form.username.$dirty && $scope.form.username.$invalid;
});

And use the isusernameinvalid (true/false) to toggle class 并使用isusernameinvalid(true / false)切换类

ng-class="{ 'has-error': isusernameinvalid }"

I know "form" is not a $scope variable, and hence inaccessible. 我知道“ form”不是$ scope变量,因此无法访问。

How do i access the validation state/class info over here? 我如何在此处访问验证状态/类信息?

If you declare the form like this 如果您声明这样的形式

<form name="formName"></form>

you should be able to access it in the controller via $scope.formName . 您应该可以通过$scope.formName在控制器中访问它。 However as always in angular you have to be careful about looking in the correct scope, so maybe set ng-controller="mycontroller" on the form tag or on some tag that contains the form tag if not done already. 但是,像往常一样,您必须小心寻找正确的范围,因此,如果尚未完成,则可以在form标签或某些包含form标签的标签上设置ng-controller="mycontroller"

It could also be that when the $scope.isusernameinvalid = $scope.form.username.$dirty && $scope.form.username.$invalid; 也可能是当$scope.isusernameinvalid = $scope.form.username.$dirty && $scope.form.username.$invalid; code runs the form hasn't been initialized in the scope yet, so accessing it returns undefined . 代码运行的表单尚未在范围中初始化,因此对其进行访问将返回undefined Declaring isuernameinvalid as a function instead should get around that: 将isuernameinvalid声明为一个函数应该可以解决:

$scope.isUsernameInvalid = function() {
    return $scope.form.username.$dirty && $scope.form.username.$invalid;
}

And then call it as a function in your ng-class directive. 然后在ng-class指令中将其作为函数调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM