Understanding Two-way Data Binding in AngularJS

Originally published at: http://www.sitepoint.com/two-way-data-binding-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:

{
  name: 'ACG',
  version: '0.0.0',
  authors: [
    'Tanay Pant <tanay1337 @gmail.com>'
  ],
  description: 'Card Generator',
  keywords: [
    'AngularJS'
  ],
  license: 'MIT',
  ignore: [
    '**/.*',
    'node_modules',
    'bower_components',
    'test',
    'tests'
  ]
}

Next, run the following command in the terminal:

bower install bootstrap --save
bower install font-awesome --save
bower install angular --save

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:

<!DOCTYPE HTML>
<html lang="en" ng-app="myApp" ng-controller="BusinessCardController">
  <head>
    <title>{{ user.name }} | Business Card</title>
    <meta charset="utf-8"/>
    <link href="path/to/bootstrap.min.css" rel="stylesheet"/>
    <link href="path/to/font-awesome.min.css" rel="stylesheet"/>
    <link href="style.css" rel="stylesheet"/>
  </head>

  <body>
    <script src="path/to/jquery.min.js"></script>
    <script src="path/to/js/bootstrap.min.js"></script>
    <script src="path/to/angular.min.js"></script>
    <script>
      'use strict';

      angular.module('myApp', [])
      .controller('BusinessCardController', function($scope){
        $scope.user = {
          name: 'Tanay Pant'
        }
      });
    </script>
  </body>
</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).

Continue reading this article on SitePoint

Hi, thanks for the simplicity ! Good tutorial.
I got a question can we get binding directly through a css file ?

Thanks, Houssem! I’m afraid at the moment that is not possible, however in your controller, you can write:

$scope.mystyles = {
 .myclass: {
  display: block
 }
};

In the HTML file:

<style>{{mystyles}}</style>

@Tanay. This is a complete tutorial, from environment set up to execution.

What’s your opinion on AngularJS 2.0? By all means, I’m no expert in AngularJS but I’ve heard there was a civil war going in the community.

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 :slight_smile:

I’m not sure if you responded my question but I’ve heard many that abandon AngularJS due to 2.0 being dramatically different and not being backward compatible. Some even worry that 2.0 may kill AngularJS community.

Well, I agree with what you have heard, but AngularJS is still widely used by big projects. Empires rise and fall all the time :wink: But I for one believe that would not be the case with Angular.

Yeah… Angular had such a popularity. One developer left Google’s Angular Team and started his own framework

http://eisenbergeffect.bluespire.com/leaving-angular/

Interesting Article.

@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…

The one thing that Angular has going for it is that it is backed by Google.
This table with a few metrics on community comparing Angular, Ember and backbone makes quite interesting reading.

I’m not so sure… I’ll wait and see. Who’s to say that Angular 3.0 will be the same… no upgrade path. Other frameworks are easily replaced but MVC frameworks are kind of like heart transplant. I suppose using AngularJS 2.0 is ok for now…assuming they’ll supported for at least 3~5 years or so. I hope I’m wrong but I feel AngularJS is heading downhill. I am NOT saying AngularJS 2 is not a good framework. Just saying that there is a chance that Application built with AngularJS 2 may not have upgrade path to AngularJS 3. From business perspective, this is a very bad ROI.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.