0

我已成功使用$watch表单 ngModel Controller$error属性来监视无效状态,然后title在有效状态变为无效时将自定义错误消息添加到 HTML 元素工具提示(属性)。

以下是代码:

var addValidationMessage = function (ngForm, elm, errAttr, errMsg, msgVar1) {
    //Use $timeout to ensure validation rules are added and compiled.
    //After compile is done then will start watching errors
    $timeout(function(){
        var elmModel;
        var ngModelName="";
        //Get the name of the 'ng-model' of the element being validated
        elmModel = angular.element(elm).controller('ngModel');
        if (elmModel && elmModel.$name) {
            ngModelName = elmModel.$name;
        }
        if (!ngModelName) {
            ngModelName = angular.element(elm).attr('ng-model');
        }
        if (ngModelName) {
            scope.$watch(ngForm.$name + '.' + ngModelName + '.$error.' + errAttr,
                function (newValue, oldValue){
                    //console.log("elm.id =", elm.id);
                    //The validation error message will be placed on the element 'title' attribute which will be the field 'tooltip'.
                    //newValue == true means there is error
                    if (newValue) {
                        var msgVar1Val;
                        //Perform variable substitution if required to get the final text of the error message.
                        if (msgVar1) {
                            msgVar1Val = scope.$eval(angular.element(elm).attr(msgVar1));
                            errMsg = errMsg.format(msgVar1Val);
                        }
                        //Append the error to the title if neeeded
                        if (elm.title) {
                            elm.title += " ";
                        } else {
                            elm.title = "";
                        }
                        elm.title += errMsg;
                    } else {
                        //Remove the error if valid.
                        //child.removeAttribute('title');
                        if (elm.title) {
                            //Replace the error message with blank.
                            elm.title = elm.title.replace(errMsg, "").trim();
                        }
                    }
                });
        } else {
            //console.warn("Warning in addValidationMessage() for element ID '%s' in ngForm '%s'. Message: 'ng-model' is not defined.", elm.id, ngForm.$name)
        }
    }, 1000);       
}

并且,上述函数在 element 指令中使用如下:

errMsg = "Number of characters entered should not exceed '{0}' characters.";
addValidationMessage(ngForm, child, 'maxlength', errMsg, 'ng-maxlength');

上面的代码在处理 1000 多个字段时会导致性能问题。换句话说,对于 1000 多个字段,它会导致 Chrome 中的执行速度减慢 10 秒。在 IE 中,它会导致处理速度减慢 1 分钟。

宗旨

是否有更好的方法来实现相同的目标?

感谢您的反馈。

塔雷克

4

0 回答 0