在AngularJS中使用指令时如何使表单无效 [英] How to invalidate a form when using directive in AngularJS

查看:119
本文介绍了在AngularJS中使用指令时如何使表单无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理SPA,并且此应用程序中的表单使用输入遮罩的文本框,该文本框是使用此处

i am working on a SPA and a form inside this app uses an input masked text box implemented using a third party library from here

我创建了一个指令来为IP地址设置掩码

i created a directive to set a mask for an IP address

angular
.module('app').directive('ipMask', [
    function () {
        return {
            restrict: 'A',
            require: '?ngModel',
            link: function (scope, element, attrs, ngModel) {        
                    element.mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {'Z': {pattern: /[0-9]/, optional: true}}});
                    element.mask('099.099.099.099');

                    scope.$watch(attrs.ngModel, function (newValue, oldValue) {
                        //????????
                    });
            }
        };
    }
]);

我的表单代码如下

    <div ng-controller="nodesListCtrl as vm">
        <form role="form" name="frmNode">

            <div class="form-group">
                <label>Node IP :</label>
                <input type="text" data-ip-mask ng-model="vm.myIp" name="CtrIp" class="input-sm form-control" placeholder="..." >
            </div>
        </form>
    </div>

如果IP地址错误,我想使表格无效.也就是说,我希望表单和控件上都为 .ng-invalid 类,直到该类保持无效为止.有什么建议 ?

i want to invalidate the form if the IP address is wrong. i.e. i am expecting .ng-invalid class both on the form and and the control as well until the time it remains invalid. any suggestions ?

推荐答案

您不需要使用$watch.只需添加解析器和/或格式化程序即可.视图更改时调用解析器,模型更改时调用格式化器. (此链接可以告诉您更多有关这些内容以及ngModelController上可用的其他内容的信息: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController ).这是一个示例:

You don't need to use $watch. Just add a parser and/or formatter. Parsers are called when the view changes and formatters when the model changes. (This link can tell you more about those, as well as the other things available on ngModelController: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController). Here's an example:

link: function (scope, element, attrs, ngModel) {        
  element.mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {'Z': {pattern: /[0-9]/, optional: true}}});
  element.mask('099.099.099.099');

  ngModel.$parsers.unshift(function(value) {
    var valid = isValid(value); // made up - use whatever validation technique based on that library
    ngModel.$setValidity('ip', valid);
    return valid;
  });

  ngModel.$formatters.unshift(function(value) {
    var valid = isValid(value);
    ngModel.$setValidity('ip', valid);
    return valid ? value : undefined;
  });
}

这篇关于在AngularJS中使用指令时如何使表单无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆