AngularJS ng-class directive with example

AngularJs ng-class directive is dynamical binds one or more CSS classes to an HTML element. which we can change according to the condition.

In this tutorial, I am going to show you

  • AngularJS ng-class directive.
  • AngularJS ng-class-even directive.
  • AngularJs ng-class-odd directive.

AngularJS ng-class directive

index.html

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<style>
.red {
    background-color:red;
  }
.blue {
    background-color:blue;
}
</style>
<body ng-app="">
<p>Choose a class:</p>
<select ng-model="home">
<option value="red">RED</option>
<option value="blue">BLUE</option>
</select>
<div ng-class="home">
  <h1>Choose back ground color for me</h1>
  </div>
</body>
</html>

AngularJS ng-class-even Directive:

AngularJs ng-class-even directive also works same as the ng-class directive. The only difference is, It will affect only even positions in ng-repeat. It will work only with the ng-repeat directive.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<style>
.blue { background-color:blue;}
</style>
<body ng-app="myApp"  ng-controller="myCtrl">
    <div ng-repeat="data in x"ng-class-even="'blue'"  >
        <h1  >{{data}}</h1>
 </div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.x = [1,2,3,4,5,6,7,8,9]
});
</script>
</body>
</html>

AngularJS ng-class-odd Directive:

AngularJs ng-class-odd directive is only affected the odd position in the ng-repeat directive.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<style>
.blue { background-color:blue;}
</style>
<body ng-app="myApp"  ng-controller="myCtrl">
    <div ng-repeat="data in x"ng-class-odd="'blue'"  >
        <h1  >{{data}}</h1>
 </div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.x = [1,2,3,4,5,6,7,8,9]
});
</script>
</body>
</html>

 

 

 

 

 

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *

three − one =