를 제거해야 할 때 제거에 추가 : 기본적으로
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()
을 사용하여 필요에 따라 특성을 설정합니다.
자세한 내용은 아래 이미지를 참조하십시오.
모두 정상적으로 작동합니다. 유일한 문제는 "이름"필드가 지워졌을 때 "Member #"필드에 필요한 속성을 제거하고 강조 표시를 지워야하지만, 클래스 ng-invalid-required
이 여전히 추가되어 강조 표시가 표시됩니다 그곳에.
이라는 NgModelController
에 대한 $error
개체가 의도 한 논리에 따라 올바르게 계산 된 것을 볼 수 있습니다.
기본적으로 여기에있는 질문은 스타일이 required
속성의 변경과 올바르게 동기화되도록하는 방법입니다.