AngularJS: Updating a Label Dynamically with User Input

11 / Sep / 2012 by raj 3 comments

After the basic introduction of AngularJS, we are all set to write code for implementing a simple functionality.

Let us consider a simple scenario. There is a textbox, and whenever the text in it changes we need to update a label dynamically. Traditional way of doing this in Javascript is to bind the change event of the textbox, such that whenever its text changes, we manually update the label inside the onChange() function. Using AngularJS, we can do this automatically without writing even a single line of javascript code.

[java]
<!doctype html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js" type="text/javascript"></script>

</pre>
<div><input type="text" />

<hr />

You entered : {{name}}</div>
<pre>

[/java]

Let’s dissect the above code line by line.
In line 2, we used ng-app attribute that represents an AngularJS directive. It basically tells AngularJS that <html> is the root element of the page. Thus, we can decide if we want the entire page to be exposed to AngularJS or only a part of the page.

In line 4, we have included the CDN hosted version of AngularJS library which is hosted by Google. Alternatively, you can download the AngularJS from here and include it using the script tag.

In line 8, we used ng-model attribute which is responsible for the powerful two-way data binding capability. Here, AngularJS binds the text entered in textbox with the variable “name”. Thus, we can access whatever is entered by a user into the textbox by accessing the “name” variable.
Note: In older versions of AngularJS, an additional attribute, ng-model-instant was required to reflect changes dynamically as the text input by user changed. It is redundant in the new version.

In line 10, we are using {{name}} to access the “name” variable and insert its value into the DOM. This is the syntax used by AngularJS for evaluating variables and expressions.

In a nutshell, whenever user changes text in the textbox, the variable “name” is updated with the new value and we access that value to update our page. The best part is, it happens dynamically with user input and we haven’t written even a single line of JavaScript code to achieve this!

We will see more of AngularJS in action in upcoming blogs.

Click the links below to read more on the AngularJS Series

FOUND THIS USEFUL? SHARE IT

comments (3)

Leave a Reply

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