Search example

ng-class if example

How to apply  ng-class if

This example provides two ways using ng-class if expression.
Following directives and services in angularjs will be used:
  • ng-classs
  • ng-model
  • ng-repeat
 <!doctype html>  
 <html lang="en">  
   <meta charset="UTF-8">  
   <title>AngularJS ng-class if example</title>  
   <script src="//"></script>  
   <link rel="stylesheet" href="">  
     .Red {  
       color: Red;  
     .Yellow {  
       color: Yellow;  
      .Blue {  
       color: Blue;  
      .Green {  
       color: Green;  
     .Gray {  
       color: Gray;  
        font-weight: bold;  
     angular.module('myapp', [])  
         .controller('ExampleController', ['$scope', function ($scope) {  
           $scope.MyColors = ['It is Red', 'It is Yellow', 'It is Blue', 'It is Green', 'It is Gray'];  
           $scope.getClass = function (strValue) {  
             if (strValue == ("It is Red"))  
               return "Red";  
             else if (strValue == ("It is Yellow"))  
               return "Yellow";  
             else if (strValue == ("It is Blue"))  
               return "Blue";  
             else if (strValue == ("It is Green"))  
               return "Green";  
             else if (strValue == ("It is Gray"))  
               return "Gray";  
 <body ng-app="myapp" ng-controller="ExampleController">  
   <h2>AngularJS ng-class if example</h2>  
   <ul >  
     <li ng-repeat="icolor in MyColors" >  
       <p ng-class="[getClass(icolor), 'b']">{{icolor}}</p>  
   <p>Other way using : ng-class="{'class1' : expression1, 'class2' : expression2,'class3':expression2,...}"</p>  
     <li ng-repeat="icolor in MyColors">  
       <p ng-class="{'Red':icolor=='It is Red','Yellow':icolor=='It is Yellow','Blue':icolor=='It is Blue','Green':icolor=='It is Green','Gray':icolor=='It is Gray'}" class="b">{{icolor}}</p>  

Here is result screen shot

If you have other ways can share to everybody.


  1. I have list of stage name.stage start with three cateogry Application,Interview,Offer using the prefix i want to show diffrent the stages with colors ex:Application-Waiting for confirmation Try to give some suggestion

  2. This comment has been removed by a blog administrator.

  3. Making a personal statement more personal could help a college admissions committee get to know you better. Giving them a chance to see something unique about you and giving them a reason to accept you is the goal of a college essay. See more mba statement of purpose sample

  4. Thank you very much. Very useful!


Popular Posts