Reusing the ngClass Directive in AngularJS

I am trying to validate a form and there is too much logic in the html page. I already use ngMessages because without it it is hopeless.

I am making an object variant of an ng class as follows

ng-class="{ 'has-error' : registerForm.username.$invalid && registerForm.username.$touched, 'has-success' : registerForm.username.$valid && registerForm.username.$touched }" 

As you can see, there is already a lot of code in the line above. I have to use this directive 6 times, so my only option, as it seems now, is to copy it to 5 other places. I tried to do something similar, but it did not work

 <form ng-init="formGroupClassObject = { 'has-error' : registerForm.username.$invalid && registerForm.username.$touched, 'has-success' : registerForm.username.$valid && registerForm.username.$touched }"> <div class="form-group" ng-class="formGroupClassObject"></div> 

I do not understand why this does not work. Do you have any other recommendations for reusing the code above?

+6
source share
1 answer

What about:

 ng-class="getFormClasses(registerForm)" 

And in your general controller:

 $scope.getFormClasses = function(form) { if (!form) { return; } return { 'has-error' : form.username.$invalid && form.username.$touched, 'has-success': form.username.$valid && form.username.$touched } }; 

If you use ng-init , the classes will not be updated when the form changes.

+3
source

Source: https://habr.com/ru/post/985914/


All Articles