Ng-Class-2

 

Lets try with new example where we are changing the classes based on checkbox selection and hasError class will apply on First Name textbox if hasError variable is set to true with ng-model directive.hasSuccess class will apply on Last Name textbox if hasSuccess variable evaluates true. This is how we add ng-class to first name: ng-class="{true:'hasError',false:'hasSuccess'}[hasError]"

 
 
 
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Welcome to LearnKode - A code learning platform</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <style type="text/css"> .hasError { border-color: red; } .hasSuccess { border-color: green; } </style> </head> <body ng-app> <div> <div class="container"> <div class="well col-md-3"> Has Error <input type="checkbox" ng-model="hasError" /><br /> <br /> First Name<input type="text" class="form-control" ng-class="{true:'hasError',false:'hasSuccess'}[hasError]" /> Last Name<input type="text" class="form-control" ng-class="{true:'hasError',false:'hasSuccess'}[hasError]" /> </div> </div> </div> </body> </html>
Output