Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse ngClass directive in AngularJS

Tags:

angularjs

I am trying to validate a form and there is just way too much logic in the html page. I am already using ngMessages because it's quite hopeless without it.

I am doing the object variant of ng-class like this

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 alot of code already in the above line. I have to use this directive 6 times so my only option as it seems right now is to copy paste it 5 other places. I tried doing something like this 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 don't understand why this do not work. Do you have any other suggestions on reuse-ability of the code above?

like image 540
Alex Avatar asked Apr 24 '15 20:04

Alex


People also ask

How do you use ngClass directive?

AngularJS ng-class DirectiveIf it is a string, it should contain one or more, space-separated class names. As an object, it should contain key-value pairs, where the key is the class name of the class you want to add, and the value is a boolean value. The class will only be added if the value is set to true.

Can we use ngIf and ngClass together?

Now you have learned the basics of Angular directives, including how to use ngIf, ngFor, ngClass, ngStyle, ngModel, and ngSwitch. You can combine them to create more complex user interfaces.

Is ngClass an attribute directive?

The Angular ngClass Directive is an Angular Attribute Directive, which allows us to add or remove CSS classes to an HTML element. Using ngClass you can create dynamic styles in angular components by using conditional expressions.

What is the use of ngClass?

The ng-class Directive in AngularJS is used to specify the CSS classes on HTML elements. It is used to dynamically bind classes on an HTML element. The value for the ng-class has either string, an object, or an array. It must contain more than one class name, which is separated by space, in the case of a string.


1 Answers

How about:

ng-class="getFormClasses(registerForm)"

And in your common 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 validity changes.

like image 152
floribon Avatar answered Oct 18 '22 03:10

floribon