Thursday, 23 March 2017

Dynamically Change Background color using Angular JS.

In this tutorial we are going to see how to change background color of an Application using AngularJs.
So let’s get started.
To know about prerequisites needed to run this example see our previous post.
First create index.html file shown as below.

<html>
<head>
<script src="angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
</html>

The code shown above will add files require to run our angular application.
Next add an textbox which takes input color from user as shown in below,

<input ng-model='bgcolor' placeholder="Enter a color name" />

Where ng-model is a directive used to assign the color value inserted by user to bgcolor property.
next add style to set background color to value inserted by user which is model bgcolor

style="background:{{bgcolor}}"

Also add ng-controller and ng-app directive to our html file.
So final index.html will look like,

<html ng-app="myModule">
<head>
<script src="angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body ng-controller="myController" style="background:{{bgcolor}}">
<input ng-model='bgcolor' placeholder="Enter a color name" />
</body>
</html>

The code written in script.js is for attaching module and controller to the view index.html.
So add module to our script.js file like this,

Var app=angular.module(“myModule”,[]);

Where myModule is our module name and [] is for  dependencies.Currently we are not using any dependencies so it will be empty.Now register the controller with our module like this,

app.controller(“myController”,function($scope){
});

Our application is now ready to be executed.
Now take input from user as shown in below image

changes background when color value is entered

As soon as we enter yellow in textbox, the background color is going to change as shown as above
So this is how we can change background color dynamically by using AngularJS.

If you have any question regarding this you can write us at testyourcoding111@gmail.com

No comments:

Post a Comment