AngularJs Toggle Class using ng-class


AngularJs Toggle Class using ng-class – It is very simple to toggle the class the class using ng-class in angularJs. Here in this tutorial we are going to explain how you can add the toggle class functionality using ng-class. You can use our online editor to edit and see the output of the example.


AngularJs Toggle Class using ng-class

You can add the toggle class functionality using the ng-class as below –

AngularJs Toggle Class using ng-class Example:

<!DOCTYPE html>
<html lang="en">
<head>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
 $scope.blueBg = true;
$scope.toggleBg = function(selectedOpt) {
	if($scope.blueBg == true){
    $scope.blueBg = false;
	}else{
	$scope.blueBg = true;	
	}
};
});
</script> 
<style type='text/css'>
.class1{	
	background:yellow;
}
.class2{	
	background:blue;
}
</style>
</head>
<body>  
<div ng-app="myApp">  
<div ng-controller="myController">  
<div style='width:200px;height:200px;' ng-class="{'class1':!blueBg, 'class2': blueBg}">{{ blueBg }}</div>
<a href="javascript:void(0);" ng-click='toggleBg();'>ToggleBg</a>
</div>  
</div> 

</body>  
</html>      

Try it »

If you run the above example it will produce the output something like this-

AngularJs Toggle Class using ng-class


Advertisements

Add Comment

📖 Read More