5 Awesome AngularJS Features

5 Awesome AngularJS Features

Tutorial Details
  • Program: AngularJS, JavaScript
  • Difficulty: Intermediate
  • Estimated Completion Time: 20 min

AngularJS is a great JavaScript framework that has some very compelling features for not only developers, but designers as well! In this tutorial, we will cover what I consider to be the most essential features, and how they can help make your next web application awesome.


The Elevator Pitch: AngularJS in a Nutshell

AngularJS is a new, powerful, client-side technology that provides a way of accomplishing really powerful things in a way that embraces and extends HTML, CSS and JavaScript, while shoring up some of its glaring deficiencies. It is what HTML would have been, had it been built for dynamic content.

In this article, we will cover a few of the most important AngularJS concepts to get the “big picture.” It is my goal that, after seeing some of these features, you will be excited enough to go and build something fun with AngularJS.


Feature 1: Two Way Data-Binding

Think of your model as the single-source-of-truth for your application. Your model is where you go to to read or update anything in your application.

Data-binding is probably the coolest and most useful feature in AngularJS. It will save you from writing a considerable amount of boilerplate code. A typical web application may contain up to 80% of its code base, dedicated to traversing, manipulating, and listening to the DOM. Data-binding makes this code disappear, so you can focus on your application.

Think of your model as the single-source-of-truth for your application. Your model is where you go to to read or update anything in your application. The data-binding directives provide a projection of your model to the application view. This projection is seamless, and occurs without any effort from you.

Traditionally, when the model changes, the developer is responsible for manually manipulating the DOM elements and attributes to reflect these changes. This is a two-way street. In one direction, the model changes drive change in DOM elements. In the other, DOM element changes necessitate changes in the model. This is further complicated by user interaction, since the developer is then responsible for interpreting the interactions, merging them into a model, and updating the view. This is a very manual and cumbersome process, which becomes difficult to control, as an application grows in size and complexity.

There must be a better way! AngularJS’ two-way data-binding handles the synchronization between the DOM and the model, and vice versa.

Here is a simple example, which demonstrates how to bind an input value to an <h1> element.

  <!doctype html>
  <html ng-app>
    <head>
      <script src="http://code.angularjs.org/angular-1.0.0rc10.min.js"></script>
    </head>
    <body>
      <div>
        <label>Name:</label>
        <input type="text" ng-model="yourName" placeholder="Enter a name here">
        <hr>
        <h1>Hello, {{yourName}}!</h1>
      </div>
    </body>
  </html>
  

This is extremely simple to set up, and almost magical…


Feature 2: Templates

It’s important to realize that at no point does AngularJS manipulate the template as strings. It’s all the browser DOM.

In AngularJS, a template is just plain-old-HTML. The HTML vocabulary is extended, to contain instructions on how the model should be projected into the view.

The HTML templates are parsed by the browser into the DOM. The DOM then becomes the input to the AngularJS compiler. AngularJS traverses the DOM template for rendering instructions, which are called directives. Collectively, the directives are responsible for setting up the data-binding for your application view.

It is important to realize that at no point does AngularJS manipulate the template as strings. The input to AngularJS is browser DOM and not an HTML string. The data-bindings are DOM transformations, not string concatenations or innerHTML changes. Using the DOM as the input, rather than strings, is the biggest differentiation AngularJS has from its sibling frameworks. Using the DOM is what allows you to extend the directive vocabulary and build your own directives, or even abstract them into reusable components!

One of the greatest advantages to this approach is that it creates a tight workflow between designers and developers. Designers can mark up their HTML as they normally would, and then developers take the baton and hook in functionality, via bindings with very little effort.

Here is an example where I am using the ng-repeat directive to loop over the images array and populate what is essentially an img template.

function AlbumCtrl($scope) {
	scope.images = [
		{"thumbnail":"img/image_01.png", "description":"Image 01 description"},
		{"thumbnail":"img/image_02.png", "description":"Image 02 description"},
		{"thumbnail":"img/image_03.png", "description":"Image 03 description"},
		{"thumbnail":"img/image_04.png", "description":"Image 04 description"},
		{"thumbnail":"img/image_05.png", "description":"Image 05 description"}
	];
}
  
  <div ng-controller="AlbumCtrl">
    <ul>
      <li ng-repeat="image in images">
        <img ng-src="{{image.thumbnail}}" alt="{{image.description}}">
      </li>
    </ul>
  </div>
  

It is also worth mentioning, as a side note, that AngularJS does not force you to learn a new syntax or extract your templates from your application.


Feature 3: MVC

AngularJS incorporates the basic principles behind the original MVC software design pattern into how it builds client-side web applications.

The MVC or Model-View-Controller pattern means a lot of different things to different people. AngularJS does not implement MVC in the traditional sense, but rather something closer to MVVM (Model-View-ViewModel).

The Model

The model is simply the data in the application. The model is just plain old JavaScript objects. There is no need to inherit from framework classes, wrap it in proxy objects, or use special getter/setter methods to access it. The fact that we are dealing with vanilla JavaScript is a really nice feature, which cuts down on the application boilerplate.

The ViewModel

A viewmodel is an object that provides specific data and methods to maintain specific views.

The viewmodel is the $scope object that lives within the AngularJS application. $scope is just a simple JavaScript object with a small API designed to detect and broadcast changes to its state.

The Controller

The controller is responsible for setting initial state and augmenting $scope with methods to control behavior. It is worth noting that the controller does not store state and does not interact with remote services.

The View

The view is the HTML that exists after AngularJS has parsed and compiled the HTML to include rendered markup and bindings.

This division creates a solid foundation to architect your application. The $scope has a reference to the data, the controller defines behavior, and the view handles the layout and handing off interaction to the controller to respond accordingly.


Feature 4: Dependency Injection

AngularJS has a built-in dependency injection subsystem that helps the developer by making the application easier to develop, understand, and test.

Dependency Injection (DI) allows you to ask for your dependencies, rather than having to go look for them or make them yourself. Think of it as a way of saying “Hey I need X’, and the DI is responsible for creating and providing it for you.

To gain access to core AngularJS services, it is simply a matter of adding that service as a parameter; AngularJS will detect that you need that service and provide an instance for you.

  function EditCtrl($scope, $location, $routeParams) {
       // Something clever here...
  }
  

You are also able to define your own custom services and make those available for injection as well.

  angular.
      module('MyServiceModule', []).
      factory('notify', ['$window', function (win) {
      return function (msg) {
          win.alert(msg);
      };
  }]);

  function myController(scope, notifyService) {
      scope.callNotify = function (msg) {
          notifyService(msg);
      };
  }

  myController.$inject = ['$scope', 'notify'];
  

Feature 5: Directives

Directives are my personal favorite feature of AngularJS. Have you ever wished that your browser would do new tricks for you? Well, now it can! This is one of my favorite parts of AngularJS. It is also probably the most challenging aspect of AngularJS.

Directives can be used to create custom HTML tags that serve as new, custom widgets. They can also be used to “decorate” elements with behavior and manipulate DOM attributes in interesting ways.

Here is a simple example of a directive that listens for an event and updates its $scope, accordingly.

  myModule.directive('myComponent', function(mySharedService) {
      return {
          restrict: 'E',
          controller: function($scope, $attrs, mySharedService) {
              $scope.$on('handleBroadcast', function() {
                  $scope.message = 'Directive: ' + mySharedService.message;
              });
          },
          replace: true,
          template: '<input>'
      };
  });
  

Then, you can use this custom directive, like so.

  <my-component ng-model="message"></my-component>
  

Creating your application as a composition of discrete components makes it incredibly easy to add, update or delete functionality as needed.


Bonus Feature: Testing

The AngularJS team feels very strongly that any code written in JavaScript needs to come with a strong set of tests. They have designed AngularJS with testability in mind, so that it makes testing your AngularJS applications as easy as possible. So there’s no excuse for not doing it.

Given the fact that JavaScript is dynamic and interpreted, rather than compiled, it is extremely important for developers to adopt a disciplined mindset for writing tests.

AngularJS is written entirely from the ground up to be testable. It even comes with an end-to-end and unit test runner setup. If you would like to see this in action, go check out the angular-seed project at https://github.com/angular/angular-seed.

Once you have the seed project, it’s a cinch to run the tests against it. Here is what the output looks like:

AngularJS Essentials

The API documentation is full of end-to-end tests that do an incredible job of illustrating how a certain part of the framework should work. After a while, I found myself going straight to the tests to see how something worked, and then maybe reading the rest of the documentation to figure something out.


Conclusion

We have covered six of the many AngularJS features that I love. I believe that these six features are essential for not only getting up and running with AngularJS, but also putting your application together in a way that is maintainable and extensible.

The website for AngularJS, http://angularjs.org, has plenty of working examples and plenty of excellent documentation. I also recommend checking out the amazing community on the AngularJS mailing list.

Let me know what you think!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Salman Abbas

    Good post. Thanks :)

  • Ali Baba

    Looks like there is new JS library comes every week.

    The Nutshell can be the same for all of them:

    BlahBlahJS is a new, powerful, client-side technology that provides a way of accomplishing really powerful things in a way that embraces and extends blah blah blah blah blah blah blah blah blah blah blah blah

    • http://www.alvinmilton.com AGDM

      How can I vote this up? Basically I feel the same way.

      • Jesus Bejarano

        I am in this group too sorry :(. but nevertheless it’s look interesting.

    • http://tombician.com Tom

      So true…

    • http://www.freshclickmedia.com/blog Shane

      I agree :)

    • http://www.redkingdesigns.com Rory

      Haha. I was thinking the same thing.

      It’s got to the point where I just skim over these “new js library!” posts.

      “Oh look. Another one”

    • http:28inch.co.uk 28inch

      And every framework post gets a comment BITCHING about new frameworks.

      “Looks like there is a new JS library comes every week blah blah blah blah”

      I. You don`t have to read it.
      II. You don`t have to use it.

      Is it so hard to believe, that this one might have some features that others don`t? I`m not even mentioning impelemnting some of the features to your choice of library/ workflow.

    • Tom Conlon

      @ali baba, @agdm, @Jesus Bejarano, @shane, @rory, @28inch

      Angular has been out for two years now: see http://stackoverflow.com/tags/angularjs/info

      So, no, this doesn’t come under the newbie JS library heading but is a solid and powerful offering.
      Tom

      • Jesus Bejarano

        The “new” label has nothing to do with the time that it have been created, is more about the time that is now ganing awerness/popularity.

      • Bart

        Says here right in the header of the page “AngularJS is a new, powerful… “

    • Alchemication

      True, I know the feeling…but you have to able to distinguish yourself – if it’s worth it or not…
      Is Angular worth it? Yes for me, but is it for you?

      Btw: Do you understand a concept of data binding? No offense, just a plain question…
      Btw2: It’s out there for 2 years (like somebody else already said) …

    • [rb]

      Yeah and they usually have a whole heap of crap like all the ng-whatever attributes on html elements.
      I dont want to pollute html with made up attributes and haveing handlebars style place holders like {{whatever}} in html code for replacement is all fine until js is disabled and the whole thing falls apart and you view all the placeholders.

      • MySchizoBuddy

        This is true for EVERY SINGLE js framework. If you disable JS then the thing falls apart.
        JS frameworks depend on JS being enabled.

        jquery is mostly used for show and hide dom elements it isn’t for making web apps. So disabling js in jquery web pages just disable the lame animations you added that’s all.

        Angular is completely different beast than jquery

      • Tad Christiansen

        I know its been 5 months, but I just have clarify this.

        “jquery is mostly used for show and hide dom elements it isn’t for making web apps”

        I totally disagree. JQuery does so much more than showing and hiding dom elements. It makes selecting and decorating elements so much easier. Not to mention all the useful ajax functionality.

        “Angular is completely different beast than jquery”

        True, but under the hood even Angular uses a light version of jquery.

      • rdgtalk

        That’s about as stupid as someone saying, “I’m not using the Java Spring framework. What the hell is up with all this IoC and DI crap they added into the language?” If it was up to guys like you, languages (and HTML) would never evolve because everyone should stick to the core library and never extend or improve it. Oddly enough, it wasn’t until years later, after all the IoC containers cropped up, that Sun decided it was a good idea and came up with CDI. the problem is, if you stick with the core of anything, you stick to one company’s set of ideas, which limits innovation.

    • Tad Christiansen

      Ali Baba

      Blah blah blah, some new JS ilbrary…innovation stinks I still want to write all my code with punch cards. :)

  • http://wouterj.nl/ Wouter J

    It is almost magic. 2 days ago I watched the I/O talk ‘The web can do that?!’ about the flexbox model, I surf to tuts+ and there is a new ‘flexbox’ tutorial.

    Today I watched a HTML5rocks live video about AngularJS and I surf to tuts+ and there is a new tutorial ‘AngularJS’…

  • Reinier Kaper

    How does this work with SEO though?
    I get that it’s pretty neat for mainly web apps, but if we take the first example and serve a header with a variable in it, we get some very awkward DOM structures for search engine.

    • Dao

      Do not let the limitations of search engine spiders translate into limitations for our applications. Search engines will adapt, or others that do will take their place.

      • John

        Are your serious or is this a joke? How about, “or your page wont get ranked and your business will fail”. No search engine has “adapted” to dynamic JS in the last 17 years, Google claims to be able too, but I see otherwise on a daily basis. If you want to succeed in SEO, you have to play by their rules.

      • MySchizoBuddy

        @John what is the search engine going to index from a web app. the name of the buttons? Web apps are different than web pages get with the program already.

        All web apps are behind a secure login anyway the search engine cannot get to it anyway.

    • rdgtalk

      Who cares? Frameworks like this are primarily designed for web “apps” – not static web pages, and you don’t give a rat’s ass about SEO when it comes to web apps.

  • http://www.alvinmilton.com AGDM

    How about examples of applications that were built with “insert JS Library” here so that its benefits and drawbacks can be discussed.

    I think that’s primarily the question most people are left with.

    me: Should I use this or not?
    me: Should I bother to learn this “tool” or not?

    • MySchizoBuddy

      Yes someone should spoon feed you the answers. so here they are
      yes
      yes

  • http://www.netsi.dk/wordpress Sten Hougaard

    Hi,
    Great post – I myself am looking into Angularjs and have played around with it. Do you know if it is possibel to create dynamic model tags in a loop? For instance if you want to dynamically create 4 sliders each should control the various parts of an element border-radius. So there should be created a ng-model=”top”, ng-model=”right”… and so on. Each of them should then be bound to the “border-xx-radius” of an element allowing you to dynamically change the radius of the element.

    As for your example regarding templates (number 2 above), the code will not work. I have rewritten it and put it on my dropbox: http://dl.dropbox.com/u/3260327/angular/angularWebapp.html

    I have also made an example of the border-radius I write about above.

    /Sten

    • Cuauhtémoc F.

      Thank you Sten, it is very useful your example… Angularjs is the future, now, do you have a github adress?

  • Adam

    Thanks for the article. While I agree with some of the other comments that there seems to be a new framework or library every other day, personally I like being given a brief intro to them by someone who has taken the time. If something in the article piques my interest, I will investigate further. Otherwise not. Simple as that.

  • Andreas

    AngularJS is one of the frameworks that interests me, so I welcome this article. But there is another one that interests me even more and that is MeteorJS, so I hope there will be more articles about that one too. I’m gonna test them both to see what’s for me. Maybe I will use them both and combine them?

  • http://nvmind.com Alex

    Angular looks nice, but I’m not sure about the elevator pitch, you could have mentioned the work “templating engine” there.

  • christ almighty

    Correct me if I’m wrong – disclaimer: I’m not wrong, so don’t you dare f**king correct me, I’m christ almighty b*tch! – but the first 3 features are all part of MVC, so there’s not 5 features there’s 3.

    Also, feature 5 is just a combination of features 2 and 4; possibly 1 and 3 as well, depending on your directive.

    Let’s get naked and crucified all up in this motherf**k!

    • rdgtalk

      Try laying off the meth before you post.

  • Todor Pavlov

    AngularJS is not like the other libraries – it is a lot easier to use – I can have a page with full dynamic behavior and almost no javascript

    • http://twitter.com/ReyHaynes ReyHaynes

      …but it is Javascr….ehh nevermind.

  • hardik

    I think angular much more then a framework. its more of behaves like and browser base component. and you can’t compare it with ember or other frameworks infect you can use angular with other frameworks if you want to :)

  • http://www.maikeldaloo.com Maikel D

    Just FYI, in your second example, image.thumbnail doesn’t exist, it might confuse some people.
    It should be image.image.
    But maybe changing the index from image to thumbnail might make more sense :)

    • http://onehungrymind.com Lukas Ruebbelke
      Author

      Good catch Maikel!

      I will see about getting a revision in.

    • http://www.johanchouquet.com J. Chouquet

      I though it was me who misunderstood the way it worked.

      Nice article though.

      I think that NetTuts is awesome to discover all of best techniques on the web, in real-time.

      But, in my opinion, it’s missing something : every article is very clear about one subject.

      Unfortunately, there are no article (I think) talking about how to integrate the new thing the article presents with existing stuff.
      Because, in a company, there is always some existing stuff. You very rarely start from the beginning.

      For example, I would love to read about integration of :

      - CanJS + Jquery Mobile
      - AngularJS + Jquery
      - MeteorJS + AngularJS
      - CanJS + MeteorJS

      Regards

  • begs

    After reading your article i tried Angular. And i’m really excited about the whole concept.
    It’s so easy to understand and has so many really nice features and clean code. Thank you for that hint!

  • Pride.Chung

    LOL
    So it’s not just me have this felling. Recently I read a post that the author evaluated 12 JavaScript MVC frameworks and decided to choose Ember.js . I’m just thinking he only covered half of these frameworks .

    Did we invent too much wheels ? Now I can’t even decide which one to try, too many options is worse than no option.

    • David Mair Spiess

      Haha the same thing happend to me :)

    • narkoz

      You can’t decide because you’re ignorant.

    • zerocool81

      I’d suggest looking at http://addyosmani.github.com/todomvc/ that compare the same project written using the different frameworks.

    • http://twitter.com/azamuddin91 Muhammad Azamuddin

      Previously I’m thinking backbone as the most important javascript framework to learn, then I saw some of positive feeling about angular JS, most of the people who have that feeling comes from backbone and move to angular, so I think I have to learn angular. this article is helpful.

    • rdgtalk

      You’re probably an iPhone user. They keep it simple: one size, and you can choose between black or white.

  • tony

    Yea angular looks like a great tool, but more backbone please :)

  • Halian Vilela

    Your second exemple shoud be:

    function AlbumCtrl($scope) {
    scope.images = [
    {"thumbnail":"img/image_01.png", "description":"Image 01 description"},
    {"thumbnail":"img/image_02.png", "description":"Image 02 description"},
    {"thumbnail":"img/image_03.png", "description":"Image 03 description"},
    {"thumbnail":"img/image_04.png", "description":"Image 04 description"},
    {"thumbnail":"img/image_05.png", "description":"Image 05 description"}
    ];
    }

  • http://okeowoaderemi.com Okeowo Omololu Remi

    Well i think the more Frameworks the better as long as each frameworks actually does something other frameworks can’t, am beginning to feel its like a fad, “create your own framework” but recently after trying out Backbone.js am kinda impressed though i’m quite satisfied with the Dojo toolkit and (jQuery+requireJS), but like i said am still open to anything “new” and actually solves a problem.

  • http://ignaciochavez.com Ignacio

    Nice, I’m checking out Angular, looks very interesting. I see that is not exactly easy to explain, for those who are interested even more check this video out from google: http://www.youtube.com/watch?v=0iQCLlu1dko

  • http://www.getthatwebsite.com Mark Foote

    For those who are not quite as experienced writing with Angular, a demo page for your examples would really help out. I realize you might have to add just a bit more to make it meaningful, that would be good too! For example, if I understand correctly, your examples for dependency injection and directives are all about setting up an ability to invoke an alert?

    Thanks.

  • David Mair Spiess

    Seems to be less boilerplate code than in backbone. Two way data binding is awesome! ember.js seems also promising, but lacks of solid documentation, so i will give angularJS a try. thanks for the introduction.
    its quite difficult to choose the right one for the job as there exist so many :)

  • Mehdi Raza

    Is it me or this Two-way binding, {{Handle bars templates}} and MVC mantra sounds familiar…. Ember.js anyone?
    To make it worse, JS frameworks that compile templates for display at runtime make for a horrific SEO story.

    • http://antp.co Michael H.

      I think AngularJS is targeted toward complex web apps more than fairly static websites. Client side work is useless when 99.9% of all clients see the same thing, which isn’t how 99.9% of web apps work.

      AngularJS is made made by Google employees which alone, for me, makes it a clear winner to any alternatives. Google’s stuff is always amazingly documented (both by themselves and the community) and maintained.

      That said, Googlebots ARE capable of rendering and understanding dynamically generated pages, though this only seems reliably available to websites that Google trusts.

    • Getulio Junior

      I tried Ember and didn´t like mainly because of the mess it does in the template files. Angular is complete different in that matters.

      Compare both and you will also see the diferences. +1 on articles about Meteor

  • Rob

    Tried it, loved it and now using it to build a new site/app. Ignore all the naysayers that haven’t even attempted to use it. When you do you’ll understand why it’s different from all the rest and in my opinion well worth a look.

  • http://web-labor.pl Web-labor

    Can get a bit tricky with the whole nesting but in the end you’ve got less code. Sadly It doesn’t seem to speed up the website as a common MVC structure or am I wrong? (just wondering, didn’t test it yet).

  • Sam

    In the second example, scope.images needs to be $scope.images

    Just in case someone is actually trying these out. =)

    function AlbumCtrl($scope) {
    $scope.images = [
    {"thumbnail":"img/image_01.png", "description":"Image 01 description"},
    {"thumbnail":"img/image_02.png", "description":"Image 02 description"},
    {"thumbnail":"img/image_03.png", "description":"Image 03 description"},
    {"thumbnail":"img/image_04.png", "description":"Image 04 description"},
    {"thumbnail":"img/image_05.png", "description":"Image 05 description"}
    ];
    }

  • http://cawoodm.wordpress.com/ Marc

    What’s this handleBroadcast stuff??

  • http://www.patibs.nl/ Ebrahim Patel

    AngularJS does exactly what it says.

  • rdgtalk

    To those wondering, “Should I use AngularJS or not?”

    From a guy whose been in this industry 30 years, with the last 15 dedicated to web application development:

    1) Stop looking for the perfect technology stack that you will be able to use from here until you retire. It doesn’t exist. I’ve been through 4 generations of technology stacks over the past 15 years as the Internet, languages, tools, hardware, etc. have all evolved, they have rendered my previous architectural decisions out-dated.
    2) You don’t have to choose just one JS framework. There’s no genie here saying you get one wish and one wish only. Develop your next project with AngularJS. If you like it, keep developing with it. If you don’t, try another. There is nothing wrong with having each project built with a different set of frameworks. Fact of that matter, that’s going to happen anyway (see my point #1 as to why).
    3) Use AngularJS, knowing full well that, in all likelihood, something better will evolve out of it and, in 5 years, AngularJS will be passé and you’ll abandon it in favor of an even better framework. That’s a good thing – not a bad thing. The use of these frameworks expose their weakness, which allows AngularJS to improve upon itself, or someone else will take the lessons learned from it and build a framework twice as good.
    4) Finally, the more frameworks you use, the greater your perspective and the more flexible your mind becomes, making it quicker and easier to move from one technology stack to another without fear or intimidation.

  • shaid99

    awesome! learned a lot.
    Thanks
    http://atomise.net

  • rr

    Very nice and detailed intro to distinguishing features of Angular. Lets just hope Google doesn’t decide to make it evil or make it go belly-up like some of their offerings did recently.