【问题标题】:How can I manage form validity from an Angular Directive?如何从 Angular 指令管理表单有效性?
【发布时间】:2016-03-13 11:30:16
【问题描述】:

我在页面上有错误跨度:

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

在指令中,我将有效性设置为真或假。

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

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

【问题讨论】:

    标签: javascript angularjs forms validation


    【解决方案1】:

    这篇文章真的帮助我解决了这种情况:

    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

    【讨论】:

      【解决方案2】:

      这取决于你的指令做什么。 查看指令的 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>
      

      【讨论】:

        猜你喜欢
        • 2016-08-14
        • 1970-01-01
        • 1970-01-01
        • 2016-03-13
        • 1970-01-01
        • 2021-04-24
        • 2017-06-17
        • 1970-01-01
        • 2016-08-11
        相关资源
        最近更新 更多