I have a form with many form inputs. All the form inputs are in directives.
I have some scenarios where I need the state of one element to affect attributes, like ng-required, of other form elements.
I'm having a hard time figuring out how to update the ng-required field/$valid in the other form elements - they remain at a state of $valid = false - I want to dynamically change the ng-required value to false so they are no longer required and the elements become valid.
In the scenario below/at plnkr, if you type text in the first Title element, the second element, Title2, should no longer be required, but it remains at $valid=false.
I've tried using a function passed into the directive, like the below, but it doesn't seem to be updating the form element's validity...
Plnkr! http://plnkr.co/edit/gCpB7dvBjiOisocjJNlz?p=preview
$scope.toggleRequired = function(content, contentFragment){
if (contentFragment.name =='title' && angular.isDefined(contentFragment.value) && contentFragment.value.length){
$scope.content.title2.required=false;
content.title2.required=false;
}else if (contentFragment.name =='title' && !angular.isDefined(contentFragment.value)){
$scope.content.title2.required=true;
content.title2.required=true;
}
}
The FormGroup class exposes an API that enables us to set validators dynamically. We need to listen to optionB value changes and based on that we add or remove the validators we require. We also call the control's updateValueAndValidity() method, as we need to recalculate the value and validation status of the control.
A dynamic form requires an object model that can describe all scenarios needed by the form functionality. The example hero-application form is a set of questions —that is, each control in the form must ask a question and accept an answer. The data model for this type of form must represent a question.
ng-pristine The field has not been modified yet. ng-dirty The field has been modified. ng-valid The field content is valid. ng-invalid The field content is not valid.
The ng-required
actually accept an expression, so there is no need to add {{ .. }}
around the variable, otherwise the expression will be evaluated only once at a compile time.
In the textFormElement.html
template, change this line:
ng-required="{{contentFragment.required}}"
to this:
ng-required="contentFragment.required"
Plunker: http://plnkr.co/edit/YLInikMU5Dl2hIpHPauy?p=preview
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With