UPDATE1: Started using ngProgress, but not giving required effect in IE.
Final Update: Best solution found. See last answer below.
The AngularJS application ha
Finally, I was able to achieve the best acceptable performance for Chrome and IE.
Following are the main changes that fixed the problem in the previous code:
//delete validationList[childID]
required='required'
instead of ng-required='true'
.Following is the updated code for directive check-if-required
:
app.directive('checkIfRequired', function($compile, $parse, $interpolate, $timeout, $q, BusinessLogic){
return {
priority: 100,
terminal: true,
restrict: 'A',
require: '?^form',
link: function (scope, el, attrs, ngForm) {
var saveIsValidationRequired;
var mainElmID = $interpolate(el[0].id)(scope);
var resolvedPromise;
var getChildren = function(el, doInterpolate) {
var resultChildren;
doInterpolate = (doInterpolate===undefined)?true:doInterpolate;
//Return list of elements which were not compiled before 'compiled === undefined'
resultChildren = $(':input', el);
//Use code below just in case we want to extract the elements which are not compiled.
//Use $interpolate to get the final result for each ID...
if (doInterpolate) {
for (var i=0; i < resultChildren.length; i++) {
if (resultChildren[i].id) {
resultChildren[i].id = $interpolate(resultChildren[i].id)(scope);
}
}
}
//resultChildren = resultChildren.filter("[id!='']");
return resultChildren;
}
//User resolvedPromise when no such promise is available.
resolvedPromise = $q.when('resolved');
//Code improvement to make this directive more general
// Since this directive can be used from within an isolated scope directive such as 'photo-list-upload', then
// additional parameters are required to make it work properly.
// Make sure all required functions are defined or report warning.
// If the function is not defined within 'scope' it will be looked up from within 'BusinessLogic.getScope()'.
// If not found at all, default is used, and warning is reported.
scope.getIsValidationRequired = scope.getIsValidationRequired ||
(BusinessLogic.getScope().getIsValidationRequired) ||
(console.warn("Directive 'apply-validation' element '%s' - function 'scope.getIsValidationRequired()' is not defined. It will always be false.", mainElmID),
function () {
return false;
}
);
//The promise 'requiredFieldPromise' is used to retrieve list of validation rules from DB
//Break Point Condition: scope.listData.photosFormName == "subjectPhotos"
scope.stopExecValidations = scope.stopExecValidations || BusinessLogic.getScope().stopExecValidations ||
(console.warn("Directive 'apply-validation' element '%s' - function 'scope.stopExecValidations()' is not defined. Dummy function is used instead.", mainElmID),
function () {
//Dummy
}
);
scope.requiredFieldsPromise =
scope.requiredFieldsPromise || (BusinessLogic.getScope().requiredFieldsPromise) ||
(console.warn("Directive 'apply-validation' element '%s' - function 'scope.requiredFieldsPromise' is not defined. Resolved promise will be used.", mainElmID),
resolvedPromise);
//If needed, stop validation while adding required attribute
//Save current flag value
saveIsValidationRequired = scope.getIsValidationRequired();
scope.stopExecValidations();
//remove the attribute `check-if-required` to avoid recursive calls
el.removeAttr('check-if-required');
//Define function to add validation message using $watch
// As soon as an error is detected, then 'title' will be set to the error
// Parameters:
// - ngForm: Angualr Form
// - elm: The HTML element being validated
// - errAttr: the name of the error attribute of the field within ngForm:
// ngFormName.FieldName.$error.errAttributeName
// - errMsg: The error message to be added to the title
// - msgVar1: optional substitution variable for the error message
var addValidationMessage = function (ngForm, elm, errAttr, errMsg, msgVar1, elmScope, elmModel) {
//Use $timeout to ensure validation rules are added and compiled and that the 'elmModel' is available.
//After compile is done then will start watching errors
$timeout(function(){
var ngModelName="";
//Get the name of the 'ng-model' of the element being validated
elmScope = elmScope || scope;
elmModel = elmModel || angular.element(elm).controller('ngModel');
if (elmModel && elmModel.$name) {
ngModelName = elmModel.$name;
}
if (!ngModelName) {
ngModelName = angular.element(elm).attr('ng-model');
}
if (ngModelName) {
elmScope.$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 = elmScope.$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);
}
//Refactor - apply validation rule for a given element with `childID`
function applyValidationElement(childID, child, childElm, elmScope, elmModel, validationList) {
//Validation rule for 'childID': related element was found, and now will apply validation rule.
var validObjects;
var errMsg;
validObjects = validationList[childID];
//Check if the element is not in "Required" list, and it has an expression to control requried, then
//... add the attribute 'ng-required' with the expression specified to the element and compile.
//No longer use `check-if-required-expr`, must report error if used.
if (!angular.element(child).prop('required') && child.attributes.hasOwnProperty("check-if-required-expr")) {
console.error("Unexpected use for attribute 'check-if-required-expr' in directive 'apply-validation' for element ID '%s'. Will be ignored.", childID);
}
if (validObjects === "") {
//This means the field is required
angular.element(child).attr('required', 'required');
}
else if (angular.isArray(validObjects)) {
//This means that there is a list of validation rules
for (var idx=0; idx < validObjects.length; idx++) {
var validObject = validObjects[idx];
var test = validObject.test || "true"; //if not exist, it means the rule should always be applied
var minLenExp = validObject.minlen;
var maxLenExp = validObject.maxlen;
var isRequiredExp = validObject.required || "false";
var readonlyExp = (validObject.readonly || "").toString().trim();
var pattern = validObject.pattern || "";
var isCAPostalCode = (validObject.isCAPostalCode || "false").toString().trim();
isRequiredExp = (angular.isString(isRequiredExp)?isRequiredExp:isRequiredExp.toString()).trim();
if (test) {
var testEval = scope.$eval(test, elmScope);
if (testEval) {
if (minLenExp) {
angular.element(child).attr('ng-minlength', minLenExp);
}
if (maxLenExp) {
angular.element(child).attr('maxlength', maxLenExp);
//For now, to improve performance, do not add validation message - if length exceeds the max
//errMsg = "Number of characters entered should not exceed '{0}' characters.";
//addValidationMessage(ngForm, child, 'maxlength', errMsg, 'ng-maxlength', elmScope, elmModel);
}
//Add attributes only if needed
if (isRequiredExp.toLowerCase() === "true") {
angular.element(child).attr('required', 'required');
} else
//If the "required" expression is '*skip*' then simply skip.
//If '*skip*' is used, this means the required validation is already defined in code
//and no need to replace it.
if (isRequiredExp && isRequiredExp.toLowerCase() !== "false" && isRequiredExp !== '*skip*') {
angular.element(child).attr('ng-required', isRequiredExp);
}
if (readonlyExp.toLowerCase() === "true" && readonlyExp != '*skip*') {
angular.element(child).attr('readonly', 'readonly');
} else
//Add readonly validation
if (readonlyExp && readonlyExp.toLowerCase() !== "false" && readonlyExp != '*skip*') {
angular.element(child).attr('ng-readonly', readonlyExp);
}
if (pattern) {
angular.element(child).attr('ng-pattern', pattern);
}
if (isCAPostalCode.toLowerCase() === "true") {
angular.element(child).attr('ng-pattern', "/^([A-Z]\\d[A-Z] *\\d[A-Z]\\d)$/i");
//Add validation message if postal code does not match the RegEx
addValidationMessage(ngForm, child, 'pattern', "Invalid postal code.", null, elmScope, elmModel);
}
//TODO: delete the validation rule after it is implemented to improve performance
// verify if deleting the key is OK and will not distroy the for-loop index
//delete validationList[childID]
//TODO: Apply only the first matching validation rule
// May required further analysis if more that one rule will be added.
break;
}
}
}
}
}
//Check of trim for Field ID is done - not needed if field ID is already timmed in `validationList`.
//BusinessLogic.getScope().mainVM.validFieldIDTrimDone = BusinessLogic.getScope().mainVM.validFieldIDTrimDone || false;
//var validFieldIDTrimDone;
function doApplyValidation(scope, el, attrs, ngForm) {
var children;
var fieldValidList;
var validationStructOpt;
var mainElmID;
children = getChildren(el, true); //Do run interpolation of elements IDs
//children = resultChildren = $(':input', el); //getChildren(el, false); //Do not run interpolation of elements IDs
mainElmID = $interpolate(el[0].id)(scope);
validationList=formView.getRequiredField();
//Get 'validationStructOpt' option:
// Option = 'onelayer' means there is no 'subform' layer
// Option = 'twolayers' means there is a 'subform' layer which is the default
validationStructOpt = validationList.$structureOpt || 'twolayers';
if (validationStructOpt === 'onelayer') {
//for (var fldIdx=0; fldIdx < Object.keys(validationList).length; fldIdx++) {
//console.log("One layer. Number of rules: ", Object.keys(validationList).length)
for (var fldIdx=0; fldIdx < children.length; fldIdx++) {
var childElm;
var child;
var childID;
var validObjects;
var elmScope;
var elmModel;
//childID = Object.keys(validationList)[fldIdx];
//if (childID.startsWith('$')) {
// continue;
//}
//childElm = children.filter('#'+childID);
//child = childElm.get(0);
childElm = children.eq(fldIdx);
child = childElm.get(0);
child.id = $interpolate(child.id)(scope);
childID = child.id;
//if (childElm.length) {
if (childID && (childID in validationList)) {
//Validation rule for 'childID': related element was found, and now will apply validation rule.
validObjects = validationList[childID];
elmScope = angular.element(child).scope() || scope;
elmModel = angular.element(child).controller('ngModel');
applyValidationElement(childID, child, childElm, elmScope, elmModel, validationList);
}
}
} else
if (validationStructOpt === 'twolayers') {
//angular.forEach(Object.keys(validationList), function(keySubform, subformIdx){
for (var subformIdx=0; subformIdx < Object.keys(validationList).length; subformIdx++) {
var keySubform = Object.keys(validationList)[subformIdx];
if (!keySubform.startsWith('$')) {
var subform = validationList[keySubform];
for (var childIdx=0; childIdx < Object.keys(subform).length; childIdx++) {
var childID = Object.keys(subform)[childIdx];
var validObjects;
var childElm;
var child;
var elmScope;
var elmModel;
//console.log(subform, validObjects, childID);
//Find the element with id = childID within the 'el' section.
//childElm = $('#'+childID, el);
//Use 'getChildren()' since the result list has ID values which are interpolated.
childElm = children.filter('#'+childID);
//console.log(el[0].id, childID);
if (childElm.length) {
//Validation rule for 'childID': related element was found, and now will apply validation rule.
validObjects = subform[childID];
child = childElm.get(0);
elmScope = angular.element(child).scope() || scope;
elmModel = angular.element(child).controller('ngModel');
applyValidationElement(childID, child, childElm, elmScope, elmModel, validationList[keySubform]);
}
}
}
} //Object.keys(validationList).length
//});
}
//After done processing all elements under 'el', compile the parent element 'el'.
$compile(el, null, 100)(scope);
//If saved flag value is true, enable back validation
if (saveIsValidationRequired) {
scope.startExecValidations();
}
}
function applyValidationTimeout() {
//Execute 'doApplyValidation()' in the next cycle, to ensure the child elements have been rendered.
$timeout(function(){
//console.log('applyValidationTimeout', mainElmID);
doApplyValidation(scope, el, attrs, ngForm);
}, 100)
}
scope.requiredFieldsPromise.then(function(success) {
//Apply validation when the Required Fields and Validation Rules have been loaded.
applyValidationTimeout();
}, function(prmError){
console.warn("Error occured in 'apply-validation' directive while retrieving 'requiredFieldsPromise' for element '%s': %s", mainElmID, prmError);
});
}
}
});
Following are the performance results for loading 1000+ fields and validation rules: