【问题标题】:AngularJS custom validation against a resource针对资源的 AngularJS 自定义验证
【发布时间】:2015-01-20 12:28:55
【问题描述】:

我有一个 Angular 表单,它可以在任何表单字段更改时对所有字段执行自定义验证。每个值的有效性可以根据表单中其他值的值而改变,因此每次编辑都会验证整个表单。

验证工作正常,但每次执行验证(每次按键)时,正在编辑的表单字段都会失去焦点。我很确定这是因为我的验证器实现存在缺陷(几个月前我在互联网上的某个地方复制了它,现在找不到了)。

问题出现在 Chrome 中,但不在 IE9 中。

下面是实现。有什么明显的我做错了,这会导致我遇到的焦点问题吗?

angular.module('myComponent').directive('myValidator', function (MyApiResource) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, ele, attrs, ctrl) {
            function myValidator(value) {
                if (value) {
                    var myObject = JSON.parse(JSON.stringify(scope.myObject));
                    myObject[attrs.name] = value;
                    MyApiResource.validate(myObject, function (uiValidationFailures) {
                        for (var attributeName in myObject) {
                            if (scope.correctionForm[attributeName]) {
                                var valid = !uiValidationFailures.filter(function (el) { return el.AttributeName === attributeName; }).length;
                                scope.correctionForm[attributeName].$setValidity('myValidator', valid);
                                if (valid && attributeName !== attrs.name && scope.correctionForm[attributeName].$pristine) {
                                    scope.correctionForm[attributeName].$setViewValue(myObject[attributeName]);
                                }
                                scope.uiValidationFailures[attributeName] = valid
                                    ? undefined
                                    : uiValidationFailures.filter(function (el) { return el.AttributeName === attributeName; });
                            }
                        }
                        return value;
                    });
                    return value;
                }
                scope.uiValidationFailures[attrs.name] = undefined;
                return undefined;
            };
            ctrl.$parsers.unshift(myValidator);
            ctrl.$formatters.unshift(myValidator);
        }
    }
});

【问题讨论】:

    标签: javascript angularjs validation angularjs-directive angularjs-resource


    【解决方案1】:

    虽然我在此处找不到您的代码有任何问题(没有进一步的上下文),但当您说时会响起警钟

    问题出现在 Chrome 中,但不在 IE9 中。

    另外,您正在谈论失去焦点的表单字段。我的猜测是可能会有一些不一致 - 也许在焦点行为中? - 在两个浏览器之间。不太可能是 JavaScript 问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 2017-05-26
      相关资源
      最近更新 更多