Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular - Dynamically changing validation requirements between form elements in directives

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;      
    }
  }
like image 554
peterr Avatar asked Jul 25 '14 19:07

peterr


People also ask

Which method is used to add dynamic validation to the forms in angular?

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.

What is dynamic forms in angular?

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.

What is pristine in angular?

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.


1 Answers

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.

like image 61
runTarm Avatar answered Sep 28 '22 00:09

runTarm