繁体   English   中英

如何从Angular Directive管理表单有效性?

[英]How can I manage form validity from an Angular Directive?

我在页面上出现错误跨度:

<span id="example" name="example" ng-model="example">
    <span ng-show="form.example.$error.exampleError">
        {{'example' | translate}} 
    </span>
</span>

我需要通过指令设置有效性,因此我将表单作为属性传递。

<form name="form">
    <my-directive form="form"></my-directive>
</form>

然后在指令内部,将有效性设置为true或false。

这是可行的,但是从设计的角度来看,因为我在表单中有一个指令,所以正在创建一个循环依赖项,然后将表单传递给该指令,所以我的问题确实是,是否存在一种更好的方法来通过传递指令的形式?

我可以创建一个存储表单状态(真/假)并使用ng-show的服务,但是我更喜欢使用$ error和$ setValidity。

本文确实为我解决了这种情况:

http://blog.thoughtram.io/angularjs/2015/01/11/exploring-angular-1.3-validators-pipeline.html

angular.module("app")
.directive('validateExample', function () {
    return {
        require: 'form',
        link: function (scope, element, attrs, ctrl) {
            if (you-want-example-to-be-valid) {
                ctrl.$setValidity("example", true);
            }else{
                ctrl.$setValidity("example", false);
            }
        }
    };
});

然后在您的html中,您将执行以下操作:

<form name="FormName" validate-example novalidate>
    <input id="example" name="example" ng-model="example"/>
</form>
<div ng-messages="FormName.$error" role="alert">
    <div class="alert-danger" ng-message="example">This error will show if example is invalid according to the directive
    </div>
</div>

请注意,我正在使用Angular的ngMessages,您可以在此处阅读更多内容:

https://scotch.io/tutorials/angularjs-form-validation-with-ngmessages

这取决于指令的作用。 看一下指令的require属性-https: //docs.angularjs.org/guide/directive

一种方法是在表单本身上使用属性指令。

angular.module('app').directive('formDirective', function() {
  return {
    require: 'form',
    restrict: 'A',
    link: function (scope, element, attrs, formCtrl) {
      //do stuff with your form using formCtrl
    }
  };
});

那你做

<form name="form" form-directive>
</form>

暂无
暂无

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

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