0
:
app.directive('checkIfRequired', ['$compile', '$timeout', '$parse', function ($compile, $timeout, $parse) {
return {
/*require: '?ngModel',*/
link: function (scope, el, attrs, ngModel) {
var children = $(":input", el);
var saveIsValidationRequired;
//Run the following as early as possible but just wait (using promise) until
// the list of required fields is retrieved from Database
scope.requiredFieldsPromise.then(function(success) {
//If needed, stop validation while adding required attribute
saveIsValidationRequired = scope.isValidationRequired; //Save current flag value
scope.stopExecValidations();
//remove the attribute `check-if-required` to avoid recursive calls
el.removeAttr('check-if-required');
angular.forEach(children, function(value, key) {
if (scope.isFieldRequired(value.id)) {
angular.element(value).attr('required', true);
$compile(value)(scope);
}
//Check if the element is not in "Required" list, and it has a function to control requried, then
//... execute the function using $watch and $parse and add the required attribute accordingly
if (!angular.element(value).prop('required') && value.attributes.hasOwnProperty("check-if-required-expr")) {
var isRequiredExpr = value.attributes["check-if-required-expr"].value;
scope.$watch(function(){
var exprValue = $parse(isRequiredExpr)(scope);
return exprValue;
}
, function (oldValue, newValue){
var isRequired = $parse(isRequiredExpr)(scope);
if (isRequired) {
angular.element(value).prop('required', true);
$compile(value)(scope);
} else {
angular.element(value).prop('required', false);
$compile(value)(scope);
}
var elModel = angular.element(value).controller("ngModel");
elModel.$setViewValue(elModel.$viewValue);
})
}
});
//If saved flag value is true, enable validation
if (saveIsValidationRequired) {
scope.startExecValidations();
}
})
//})
}
};
}]);
基本上,上面的指令中檢查是否如果需要子元素,則會使用$compile(value)(scope)
添加所需的屬性,如果不是,則會檢查是否指定了check-if-required-expr
表達式,如果是,則將使用$watch()
來評估表達式,並相應地設置必需的屬性。
有關更多詳細信息,請參閱下面的圖像。
一切工作正常。唯一的問題是,當「Name」字段被清除時,「Member#」字段的必需屬性應該被刪除,並且高亮應該被清除,但是類ng-invalid-required
仍然被添加,並且這導致突出顯示爲那裏。
您可以看到名爲super_aic_member_number
的$error
對象NgModelController
按照預期的邏輯計算正確。
所以基本上這裏的問題是如何確保樣式與required
屬性的更改正確同步?