Understanding Two-way Data Binding in AngularJS

In this tutorial I will demonstrate how two-way data binding works in AngularJS by building a dynamic business card generator. This generator will allow you to create your own virtual visiting cards, which you can personalize with your name, occupation, email, company logo, as well as links to both homepage and social media sites. You will be able to adjust both the background and text color of the card, using HTML5 color inputs and see any changes you make appear on the screen in real-time.

This is what we’ll end up with:

Getting Started

We’re going to use Bower to manage our project’s dependencies. Bower is a package manager for the web and can be installed using npm (which means you’ll need to have Node.js installed). If you need help installing Node.js (or npm) then check out this recent SitePoint article on that very subject. If you need help installing Bower, then you can check out the instructions on their homepage.

Our dependencies for this project will be the Bootstrap Framework (for styling and an accordion component), Font Awesome (for icons), as well as jQuery (on which Bootstrap depends) and AngularJS.

Assuming you have Bower installed and configured, create a new directory, cd into that directory and use Bower to initialize the project:

mkdir ACG && cd ACG
bower init

Bower will then create a bower.json file in the root directory of your project. It will also ask you a few questions, such as the name of the project, name of the author, description and so on. Under name enter “ACG” ( for Angular Card Generator) and fill the rest out as you see fit (or just accept the default values). The resultant JSON file should look like this:

This will install all the required dependencies for our project in a directory called bower_components and save the dependencies to the JSON file. It is a good idea to add bower_components to .gitignore because you do not want to upload this folder to your GitHub repository, since any contributor can install the same dependencies by running bower install in the root of the project.

The Anatomy of an AngularJS App

In the ACG folder create a file index.html and another called style.css. Add the following code to index.html:

We start the web page by adding both ng-app="myApp" and ng-controller="BusinessCardController" to the <html> tag. The ng-app directive is required to tell Angular that the whole page is an AngularJS application, while the ng-controller directive attaches a controller class to our view.

We then use the ng-bind directive in the title, so as to keep the title of the page in sync with our model, before including the relevant CSS files (in the <head>) and JS files (before the closing </body> tag). These files (apart from style.css) are all located in the bower_components folder.

Finally, we define myApp (our main module that’s loaded when the app bootstraps), as well as a BusinessCardController in which we will set up the initial state of the $scope object (the method by which our controller and view share data).

Accordions, Please!

Now we need a way to present the configuration options to the user. As we are using Bootstrap, we can make use of the collapse component—a basic accordion. The structure of an accordion panel is as follows:

These values (which were bound to the input elements using ng-model, previously) can now be referenced inside of expressions—JavaScript-like code snippets that are usually placed inside curly braces. This means that if we write {{ user.name }} anywhere within our ng-controller, it will evaluate to whatever user.name is currently set to.

We can make use of this when creating our card. Creating a title that automatically updates according to whatever was entered into the “Full Name” input element, is as simple as:

<h1>{{ user.name }}</h1>

Here’s a second iteration with everything working as expected (I’ve removed the second accordion due to space restrictions). You will need to update index.html and style.css with the HTML and CSS from the CodePen. The JavaScript goes inside our controller.

Please note that for the card’s logo, we are using a directive called ng-src. This is because if we just use src, the browser will start fetching the URL in raw format before AngularJS replaces the expression. We are also using ng-href for the same reason.

Social Links

An important part of the code is the social links button. We have used the ng-if directive (which removes or recreates a portion of the DOM tree based on an {expression}) in both the Facebook and Google+ username columns, but not in the Twitter profile, as it is required. This means that the Facebook and Google+ icons will only be displayed if a user has entered their respective profile URLs.

Now we consider the case where the user neither has a Facebook nor a Google+ profile. That will mess up our design, since it leaves a big empty space in front of the twitter icon. We can solve this problem by using the ng-show directive on the span tag. This displays the user’s full Twitter handle only if the Facebook and Google+ URLs are not set. Pretty easy, huh?

Conclusion

I hope that the Card Generator helped you in learning the basic concepts of data binding in AngularJS. You can find a complete demo of the code on CodePen, or you can clone the code for this article from GitHub. I encourage you to fork the repository, play around with the code and see what cool things you can come up with.

Tanay Pant is an Indian author, hacker, developer and tech enthusiast. He is known for his work on Learning Firefox OS Application Development, which was published by Packt. He is also an official representative of Mozilla, and has been listed in the about:credits of the Firefox web browser. His personal website is tanaypant.com.

Sponsors

Replies

Well, AngularJS is good for making web applications, however if I were working on a mobile application, Vue.js or React.js would be the libraries of my choice since Angular is a bit heavy, in my opinion. But yes, AngularJS does make life easy

@sg707 there will be a couple of articles on the Aurelia framework coming to the JS channel in the next couple of weeks. I think Aurelia could become a real contender on the framework scene.

As regards what happened with Angular 2.0 - it will be a complete rewrite of the framework. There is currently no upgrade path from 1.x and as you can imagine, that caused quite a furore. You can read all about that here: http://www.sitepoint.com/whats-new-in-angularjs-2/

Never heard of that one but I'm not surprised that others will take advantage of this opportunity. If Aurelia ever gets a 'In Action' book from manning then I'd definitely check it out.

Since there is no upgrade path, I believe Angular community will lose trust on next major iteration.. Who's to say that it's not backward compatible or no upgrade path? As a technical enthusiasts, I wouldn't care that much as long as it's fun to use it. From business perspective... it looks pretty horrible ROI. I think it would be hard to convince to use Angular 2 to upper management...