0

5 Reasons to Use (and Love) Angular JS

AngularJS-large

Having written a post about 5 reasons to love Backbone JS and owing to the huge debate that exists between that and the Google owned Angular JS framework, I thought it only fair that I review and post 5 reasons to use Angular as well.

Doing my research and development using both tools, I've found numerous people highlight, compare and debate the pros and cons of the distinct differences between the two approaches. Unlike those other posts, I will simply list what I think the most beneficial aspects of Angular to be. You can reference my post on Backbone and form your own opinion on which is better suited to your task based on that.

So without further ado here are 5 reasons to use and love Angular JS.

  1. HTML Directives

    Angular is written from the perspective of putting more horsepower under the hood of your HTML, an approach known in the Angular world as "Directives".

    At first, this approach seemed somewhat counter-intuitive to me. Why do I want to pollute my nice, clean semantically appointed HTML 5 DOM markup with a bunch of proprietary Angular driven attributes? This violated my idea of W3C standards compliance, streamlined HTML 5 code and loosely coupled coding.

    But hold on. What if those HTML attributes were automatically connect to functions that perform routine and straightforward actions behind the scenes, thereby eliminating the need for some (or maybe a big chunk) of laborious JS code? And what if that directive based approach promotes a DRY concept and you could write it so that you could reuse those same directives elsewhere in your app (or other apps as well?)

    Think of it like adding a central vacuum outlet to different parts of your home so you don't have to keep grabbing the actual physical vacuum every time your kid spills their cereal in the morning (which if you live in Casa del Foxy is pretty much every single day).

    Angular Directives are attributes that are affixed to DOM elements. During bootstrapping, Angular crawls over the DOM (no Angular doesn’t parse the HTML itself, it traverses the actual rendered DOM) and matches directives to DOM elements.

    Some examples of built-in and handy angular directives include:

    • ngClick – Handles mouse click events. An inline replacement for in onClick handler in your HTML or a separate $('#element').on('click', function() {}); call as handled with JQuery.
    • ngSubmit – Override form actions in favor of a custom submit function
    • ngController – Assign an Angular controller to an HTML element (such as a div)
    • ngShow/ngHide – Show or hide an HTML element based on a conditional View Model value
    • ngModel – Assign a form field value to a ViewModel for instant two way data binding

    The true power in this feature comes from the fact that you can even write your own custom directives and add them to your application as well, thereby further streamlining common routines into functions that are simply called by placing the directive in your HTML.

    Example:

    Directive JS:

    angular.module('app.directives', []).
        directive('appVersion', ['version', function(version) {
        return function(scope, elm, attrs) {
        elm.text(version);
        };
        }]);

    HTML:

    <div id="version" app-version></div>

  2. Dependency Injection

    Dependency Injection is nothing new in the back-end development world, but in the JavaScript world, it's painfully been slow to become a part of our coding workflows. Standard practice has always been to code what you need where you need it when you need it.

    Tight coupling? Who cares, this is JavaScript not an enterprise Java application.

    Duplicate resources? No problem. Handle it with a JavaScript include. We'll instantiate the same dependent objects 500 times because we think JavaScript is not the same as a structured complex backend application. Well guess what. It's getting to be that way.

    Luckily, server side sensibilities have slowly but surely been creeping more and more into the front end development workflow and Angular has put Dependency Injection front and center as one of its biggest built-in benefits.

    So what is dependency Injection and why should we be concerned with it? James Shore called it "…a 25-dollar term for a 5-cent concept." He also explained it means "giving an object its instance variables". Simply put, you pass necessary resources to functions or classes rather than create them ad hoc.

    Examples

    Inject Dependencies during instantiation:

    angular.module('ccn-main.controllers', []).controller('LoginController', ['$scope', 'loginService', function($scope , loginService) {
    // Login functionlaity
    }])

    You can also use:

    LoginController.$inject = ['$rootScope', '$scope', '$location', '$route', '$routeParams', 'loginService', 'localStorageService','storeCredentials'];

    This allows you to specify a library of services, factories or providers and then seamlessly use them anywhere in your angular application. Simply pass in the service name that you need and Angular takes care of getting the resource and making it available to you.

    Where this all comes full circle in in the testing arena where injected resources can be mocked and stubbed out rather than specifically created within the class. Less specific means more generic which means more reuse.

  3. 2-way Data Binding

    Once again, data binding is in no way a new idea. One of Flex's main selling points was its dead simple front-end data binding as a go-to feature when it arrived almost 10 years ago. HTML has actually been no stranger to data binding either. Microsoft introduced Data Islands in IE way back in 1999 when they created the XML Request object. But a true dynamic data binding solution for JavaScript has been painfully slow to find its way into common development workflows. It's gained some recognition and support with great libraries like KnockoutJS, but it's still hardly a mainstream concept.

    What are the benefits of data binding?

    1. Removes the need for the developer to manual monitor a data source and refresh the view when the data changes
    2. Removes dependency on manually accessing values
    3. Removes the need to explicitly handle user driven events to access data

    Angular accomplishes this using a methodology known as the ViewModel approach. The ViewModel abstracts the data from the view and serve as a mediator between in and the data model itself. Think of them as the glue behind event driven data bindings. Since Angular doesn't have a concept of a true model class (models are really basic JavaScript objects), you can write services or providers to act as model presenters.

    angular_flow_data_binding

    Angular also includes two-way data binding as one of its core features. Enabling data binding is accomplished in one of two ways:

    Apply Data Model value via $scope

    angular.module('app.controllers, []).
    controller(homeController, ['$scope', function($scope) {
    $scope.myVar = 'My Value";
    }]);

    Inline HTML Example:

    <input type="text" data-ng-model="myVar" size="30" />

    Either way, you can easily reference this value and watch it update in real time by using it in an Angular HTML expression:

    <div id="displayElem">{{ myVar}}</div>

    Angular also includes a powerful $watch mechanism so you can assign active listeners for data binding changes and react to them automatically.

    Data binding, while powerful, can however a tricky two way street. It can provide seamless support for keeping data in-sync with the user via the UI, but it can also add unnecessary complexity to applications where not necessary as well as memory and CPU overhead. As with any feature, it's up to the developer to use their power responsibly.

  4. HTML Partials

    One of Angular's features that really took me by surprise (in a good way), was it's handling of HTML Templates. With JS Template tools like UnderscoreJS, Handlerbars or even DustJS, the templates are typically stored as strings or in many cases, separate blocks of code. You add functionality by intermixing custom blocks of template code (using <% %> tags for Underscore and the {{ }} method for Handlerbarsor single brackets {} for Dust).

    While Angular also used double brackets for its expressions, the similarities end there.

    Using its directives approach. Angular lets you use real HTML markup for your templates and partials. You can augment them with built in or custom directives and add placeholders for bound ViewModel data with the handlebars like {{ }} syntax. You can also embed calls to custom data filters within your template as well. There's no messy scripting or custom templating markup necessary within this approach. You can save that for your actual directives and controllers. The browser interacts with the rendered DOM elements that the Angular compiler (remember $compile) assigning directives and watchers for necessary elements.

    Another nice addition in Angular is the ng-view directive. Adding this directive to a <div> element within your application allows you to automatically place templates into that div using Angulars built in routing functionality simply by specifying the template path in the route config. Angular takes care of the rest.

    The greatest advantage of Angular's templates are that instead of requiring or adding a complete templating tool into the framework, Angular simply combines many of its most powerful features to allow you to create powerful HTML templates to use and reuse. Smart Google, very smart indeed!

  5. JQuery is baked right in, or is it?

    One of the things that surprised me about Angular was to learn that it was integrated support for JQuery built right in. It utilizes many functions and can actually act like an abstraction from JQuery itself. But what if you don't want to add in JQuery (or even the lighter smaller Zepto library) into your application?

    Never fear. Angular's developers thought of this and actually crafted a lite implementation of Jquery called jqLite. So if you remove the JQuery libraries include from your app, Angular simply switches over to its own internal JQuery library and uses that instead. Mind you, it's not a full featured JQuery, more of a stripped down version, but the Angular devs seem confident it provides everything you need should you choose to remove the full library.

    From the Angular web site:

    jqLite is a tiny, API-compatible subset of jQuery that allows Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most commonly needed functionality with the goal of having a very small footprint.

    More information is available on the Angular docs site.

More to love

A few (OK a lot) more reasons (many of which could become a future posts themselves):

  • Tight unit-testing integration support – Write code and unit tests in parallel
  • Modular design allows multiple modules to be declared and used on a single page (though not sure why would have to do this as yet)
  • Built in REST communication using $http and $resource services
  • Filters for Angular's expression based template support
  • Lots of third party libraries to add additional features
  • Alignment in direction for Angular road map with some ECMAScript 6 initiatives.

So there you have it.

Resources

Interested in getting started or even more familiar with AngularJS?

As always, have fun and get coding!

jfox015

Jeff Fox is an almost twenty year web front end/ digital user experience technology leader. He cut his teeth in the web's early days and has worked for fortune 100 companies, small startup agencies and several companies in between. In addition to being a passionate developer and technical speaker, Jeff is a dedicated tech and sci-fi geek gladly indulging in Doctor Who and Star Wars marathons. He is also a talented musician, writer and proud father of three little Foxies. And don't get him started about his San Francisco Giants.

Leave a Reply

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