Change Background Color Dynamically Using AngularJS

Introduction

This article describes how to change the website background dynamically using AngularJS. In AngularJS there is one directive "ng-style" that can change Cascade Style Sheet (CSS) dynamically as you want at runtime.

In this article I am using the example of changing the website background color dynamically at the runtime.

Step 1

First of all you need to add an external Angular.js file to your application, for this you can go to the AngularJS official site or download my source code and then fetch it or click on this link and download it:
ANGULARJS.

After downloading the external file you need to add this file to the Head section of your application as in the following:

<!doctype html>
<html ng-app>
  <
head>
    <
script src="http://code.angularjs.org/1.2.6/angular.min.js"></script>
 </
head> 

Step 2

Now I am creating various for many colors inside the body tag and binding different color styles with "ng-click" directive.
 
<body>
  <input type="button" value="Red" ng-click="myStyle={background:'red'}">
  <
input type="button" value="Green" ng-click="myStyle={background:'green'}">
  <
input type="button" value="Blue" ng-click="myStyle={background:'blue'}">
  <
input type="button" value="Yellow" ng-click="myStyle={background:'yellow'}">
  <
input type="button" value="Lime" ng-click="myStyle={background:'lime'}">
  <
input type="button" value="Magenta" ng-click="myStyle={background:'magenta'}">
  <
input type="button" value="Pink" ng-click="myStyle={background:'pink'}">
  <
input type="button" value="White" ng-click="myStyle={background:'white'}"> 
 
Step 3: Now I am creating a division using a DIV tag and binding the button's style (myStyle) to the DIV using "ng-style" directives.
 
  <div ng-style="myStyle" >
    </
BR></BR></BR></BR></BR>
    <
Center>
    <
h1>Hello</BR>
     C-Sharp
</BR>
     Corner
</BR>
    POST BY:SOURABH SOMANI
    </H1></center></BR></BR></BR></BR></BR>
   </
div>
 
Output
 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now