JavaScript Data Binding with AngularJS Part I – Getting Started



In a previous post I talked about where I see things moving when it comes to the world of client-side JavaScript development. Although a lot of applications are still being built using control-oriented programming with JavaScript frameworks like jQuery, I think that the the development landscape is gradually embracing a more data-oriented programming approach and starting to take advantage of data binding frameworks that make it easier to build and maintain CRUD applications.

In this post I’m going to introduce one of the JavaScript data binding frameworks that can be used for data-oriented programming called AngularJS and show how it can be used. I’ve been experimenting with AngularJS a lot lately and like what I’ve seen up to this point. I’ll follow this post up with additional posts that drill-down into the framework more and provide details on pros and cons I’ve found. If you’re interested in seeing alternative data binding frameworks check out my earlier post.


Getting Started with AngularJS


So what is AngularJS and why is it worth taking a closer look? To answer that question take a moment to think about the features provided by HTML. It’s no secret that it wasn’t designed with dynamic applications in mind – it’s a static markup language after all. With raw HTML you can’t perform looping operations that create new elements, filter UI elements as other elements change, or perform a variety of other tasks that dynamic Web applications require. When compared to Flex, Silverlight, WPF, and other UI frameworks it’s quite limiting. We work around the limitations by generating HTML dynamically on the server or by using JavaScript frameworks like jQuery to manipulate the DOM on the client-side.

AngularJS extends HTML to support dynamic applications which means it’s well suited for CRUD-centric types of applications. For example, it allows <option> tags in a <select> to be dynamically generated without having to write custom JavaScript code to perform that task, tracks changes made to UI elements and the data they’re bound to, provides filtering/sorting support, and much more. The AngularJS documentation (http://docs.angularjs.org/guide/overview) words it this way:

“Angular takes another approach. It attempts to minimize the impedance mismatch between document centric HTML and what application needs by creating new HTML constructs. Angular teaches the browser new syntax through a construct we call directives.”

AngularJS frees you from having to do the following:

  • Register callbacks
  • Manipulate the DOM programmatically
  • Move data in and out of the UI manually with code
  • Writing a bunch of initialization code just to get started

Here’s a list of features that it provides out of the box.

  • Data binding
  • Data filtering/sorting
  • Data templates
  • Ajax support
  • Form validation
  • Routing
  • History support
  • Deep linking
  • Modular and reusable components
  • Loosely coupled architecture (dependency injection)
  • MVC-style applications
  • Architected with unit testing in mind

You can see that AngularJS is much more than a simple data binding framework – it’s more of a client-side JavaScript application framework. If you don’t like a particular feature that AngularJS provides you can inject custom code using the dependency injection functionality that’s provided. I won’t cover that topic here but you can find additional details about it and many other topics in the AngularJS docs.

To help get you started with AngularJS I’ve put together a “Hello World” type tutorial that I plan to follow-up with additional posts in the future. Let’s jump in and take a look at the basics.


Step 1: Get the Script

To get started using AngularJS you’ll need to grab the script from http://www.angularjs.org (or from their github site) and include it in your page.


<!DOCTYPE html>
<html>
    <head>
        <script src="js/libs/angular-[version].js"></script>
    </head>
    <body>
        ...
</body> </html>



Step 2: Add the ng-app Directive


Next, you’ll need to add an AngularJS directive named ng-app into the page that defines your application root. You can put ng-app on the <html> tag or on a tag somewhere else in the document (such as a <div>) if only a portion of a page needs AngularJS functionality. AngularJS initializes when the DOMContentLoaded event fires and then looks for the ng-app directive.

Here’s an example of defining the ng-app directive on the <html> element. This example doesn’t assign a value to the directive but in a future post I’ll show how ng-app can be used to define custom application modules that provide additional functionality such as routing, REST calls, and more.


<!DOCTYPE html>
<html ng-app>
    <head>
        <script src="js/libs/angular-[version].js"></script>
    </head>
    <body>




...
</body>
</
html>



Alternatively, you can define the application root programmatically if you’d prefer to go with a more jQuery-style approach:


<!DOCTYPE html>
<html>
  <head>
    <script src="js/libs/angular-[version].js"></script> 
<script> angular.element(document).ready(function () { angular.bootstrap(document); }); </script> </head>
<body>

...
</body>
</
html>



Note that jQuery can be used with AngularJS but it isn’t required.



Step 3: Add a Control with an ng-model Directive


Once the ng-app directive is added you can start using AngularJS’s data binding functionality. You can do simple data binding which I’ll show here or bind to objects that define properties and functions. To get started, add a control such as a textbox that has another AngularJS directive named ng-model on it. The ng-model directive defines the property of the model that you’ll bind to. In this example I don’t have a model object (I’ll show how to create one in a future post) and will bind the “name” property to text in the page.


Name: <input type="text" ng-model="name" />



To bind another part of the page to the value of the textbox simple “mustache” brackets ({{ and }} brackets) can be used. This is common with template frameworks like Mustache.js and others. An example of binding to the ng-model value defined on the textbox is shown next:


Welcome to AngularJS {{name}}



And that’s it! You’ve just performed your first AngularJS data binding operation. As the textbox value changes the {{name}} binding will automatically change as well. Try it out in the following live example (you’ll need to click on the “Result” tab below to run it):


Conclusion

I’ve barely scratched the surface when it comes to building data-oriented applications with AngularJS – the goal with this post is to provide a rudimentary sample. In the next post I’ll show how AngularJS can be used to bind to model object properties and perform two-way data binding.

comments powered by Disqus

11 Comments

  • Nice intro Dan. Angular is a nice/rounded library that covers so much more than data binding. As you say, its more of a client side framework that covers a lot of important areas. Someone will always ask which library is the best to use, but I like to keep it loosely coupled so we can pick and choose. It seems new ones surface every other week.

    Looking forward to your posts.

  • Thanks JasonK - fixed the URL.

    Dan

  • Thanks Dan.
    Would look forward, how we should use Angular with Microsoft.NET web-stack. Should we use ASP.NET-MVC or better server side option would be Web-API? as "MVC" part is being taken care by Angular itself.
    Also decade old question of having central validation logic of data come-up again. How well can we apply "DRY" in framework like Angular, where validation logic of html form happens to be at Domain layer "also :("

  • Thanks Dan - always curious on new libraries that can streamline Javascript code.

    How would you compare Knockout with AngularJS?

    LarsM

  • The way you wrote this post not only is informative but also interested me to data-oriented js.
    Thank you.
    Can't wait for your second post

  • Thanks so much for taking the time to do this. I've been working exclusively with wPF for a few years, knowing I was dropping behind with browser based technology. This looks like the right spot to jump back in.

  • Will:

    Glad to hear it's useful to you. You're definitely hitting things at the right time if you're coming from WPF. It's hard to use another framework if it doesn't have the data binding you're used to (like in WPF) and although HTML and JavaScript don't natively support data binding, some of the frameworks like KnockoutJS and AngularJS are doing a good job filling in the hole.

    Dan

  • vijaya:

    I appreciate the comment. I'm glad data-oriented programming appeals to you - very useful stuff.

    Dan

  • LarsM:

    KnockoutJS and AngularJS are similar (in general) when it comes to data binding. They both can do one-way or two-way binding. AngularJS is more of a complete client-side framework though with a lot of additional functionality as mentioned in the post. If you just need data binding and templates then KnockoutJS is a smaller option (size-wise) and really nice to use. If you want more of a complete client-side framework including routing, data binding, ajax calls, history support, validation, and more then AngularJS is worth looking into.

    Dan

  • Sutikshan:

    By using a framework like AngularJS you definitely end up cutting out a lot of the "normal" server-side code. The server becomes more of a data server that serves up JSON, XML, or whatever the client requests and isn't as focused on generating HTML, etc. I'm pretty excited about what the new Web API functionality offers for the purpose of sending data.

    Going with something like AngularJS really depends on the app though and how much you want running purely on the client vs. the server.

    As far as the DRY question, I don't know that I have a great answer for that one aside from saying that "yes" you can write very modular (and testable) code that is reusable with AngularJS.

    Dan

  • What you are showing is repeated everywhere. It would be more helpful if you were more Visual Studio specific (if that's what you are using) eg, project type, solution structure, deployment, etc. Thanks.

Comments have been disabled for this content.