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

时间:2016-03-13 11:30:17

标签: javascript angularjs forms validation

我在页面上有错误范围:

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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这取决于你的指令。 查看指令的require属性 - https://docs.angularjs.org/guide/directive

一种方法是在表单上使用attribute指令。

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>
相关问题