本文介绍了如何使用角度时,指令失效形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个水疗中心和在此应用中一种形式的工作使用使用第三方库从的

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) {
                        //????????
                    });
            }
        };
    }
]);

在我的形式code看起来像

where my form code looks like

    <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-无效类的形式和与控制,以及直到时间它仍然无效。有什么建议么 ?

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 ?

推荐答案

您不需要使用 $观看。只需添加一个解析器和/或格式化。当视图变化和格式化当模型改变解析器被调用。 (此链接可以告诉你更多关于这些,以及其他可用的东西放在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;
  });
}

这篇关于如何使用角度时,指令失效形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 18:38