Angular - Dynamically changing validation requirements between form elements in directives

I have a form with many input forms. All form inputs are in directives.

I have some scenarios in which I need the state of one element to influence attributes, such as ng-required, of other form elements.

It is difficult for me to determine how to update ng-required field / $ valid in other form elements - they remain in the state $ 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 script below / in plnkr, if you type in the first Title element, the second Title2 element is no longer required, but it remains equal to $ valid = false.

I tried using the function passed in the directive as shown below, but does not seem to update the validity of the form element ...

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;      
    }
  }
+4
source share
1 answer

ng-requiredactually takes an expression, so there is no need to add {{ .. }}around a variable, otherwise the expression will be evaluated only once at compile time.

In the template, textFormElement.htmlchange this line:

ng-required="{{contentFragment.required}}"

:

ng-required="contentFragment.required"

Plunker: http://plnkr.co/edit/YLInikMU5Dl2hIpHPauy?p=preview

Hope this helps.

+11
source

All Articles