javascript - 如何通过 Angular 指令管理表单有效性?

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

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

我可以创建一个存储表单状态(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

关于javascript - 如何通过 Angular 指令管理表单有效性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35969681/

相关文章:

javascript - Angular 中的 ng-repeat 递归

javascript - AngularJS : how to create DOM and bind to a model based on arbitrary hierarchical data

php - 使用它的 id 设置 Symfony2 实体表单字段

javascript - 如何使用 JavaScript 检查单选按钮是否被选中?

php - wp_mail() + Ajax + ValidationEngine + $wpdb->插入

javascript - 将 $scope 传递给 Angularjs 中的服务是否不合适,如果是,为什么?

javascript - 在 Html 中调用 JavaScript 函数

javascript - ng-repeat 在悬停时连续发射

javascript - ajax成功功能无法更改按钮文本

javascript - 无法使用 Object.keys(doc).forEach 读取未定义的属性