The Blog

6

Mar

AngularJS for jQuery Developers

AngularJS is a sweet web app framework. It comes with decent official documentation and samples, it looks superior among a large number of frameworks in an almost-real-world application test (the famous TodoMVC project), and there are cool presentations and screencasts about it all over the web.

But for a developer who has not used frameworks similar to Angular before, and has mostly worked with JavaScript libraries like jQuery, there may be some difficulty in shifting from the jQuery mindset to the Angular mindset. At least there was for me, and I’d like to share some notes–maybe this will be useful to someone.

Not a Library

The first thing to understand about AngularJS is that it’s fundamentally a different kind of tool. jQuery is a library. AngularJS is a framework. With libraries, your code decides when to call a particular function from a library. With frameworks, you implement callbacks, and the framework calls you when it decides to.

The difference is easy to understand when you think about what happens at runtime. What is jQuery doing at runtime? Mostly, nothing. Any execution of code within jQuery happens in response to your code triggering some jQuery function, prompted by some DOM event.

At loading time, Angular turns your DOM tree and javascript into an angular app. The HTML with Angular directives and filters is compiled into a tree of views, the corresponding scopes and controllers get attached to them, and internal application loop ensures data binding between the view and the model. This is real MVC stuff, with very clean separation between view, controller and model. You can think of the main event/rendering/binding loop as of one that’s running all the time, calling your controller core as needed.

Every time Model is updated – either through an asynchronous AJAX call, or through direct manipulation somewhere in controller code, Angular re-runs its $digest loop, updating the data bindings and keeping everything in sync.

Declarative, rather than Imperative

Unlike some other libraries and frameworks, Angular does not treat HTML or JavaScript as a bug that needs to be fixed (I’m looking at you.) Instead, it augments it in such a natural way that you can’t believe you did not think of it yourself. This is easier to show than to explain.

Let’s say we want to show/hide an element based on a checkbox state. In jQuery, we would do something like this:

Notice that the JavaScript code treats DOM in an imperative manner: take this node and that attribute, look at its value, do this or that.

Now let’s see the same in Angular terms:

<input ng-model="showSpecial" type="checkbox">
<div ng-show=”showSpecial”>
This content will disappear and reappear if you click the checkbox above
</div>

This is it! No code at all, just a very clear declarative way of specifying bindings and rules. Here’s a live version you can play with: http://jsfiddle.net/Y2M3r/

Direct manipulation of the DOM is not only unnecessary, it is discouraged in the Angular approach. The DOM should be specified in views, data in scopes, functionality in controller, any non-trivial transformations in custom filters and directives.

This clean separation of concerns seems like a lot to digest at first, but when the project gets large, it pays off tremendously: the code is easy to maintain, easy to separate into modules, convenient to test and diagnose.

Two-way Data Binding

Binding a DOM value to a model in a controller scope makes it truly linked to the scope variable. You probably know this from the docs and demos, but I just can’t help mentioning it. It’s one of the huge “wow” moments in the first impressions you get from Angular.

Dependency Injection

Forgive me for sounding opinionated, but Angular has the most elegant way to handle dependencies in the world.

Say, you have a JSON data source wrapped into a $resource on Angular side:

DataSource = $resource(url, default_params, method_details)

– see documentation for details. Any controller that needs to use this JSON data, can do so by including DataSource as one of the controller parameters. That’s all that is needed. This is a single piece of magic that continues to amaze me every day I work with AngularJS. You need to make an asynchronous HTTP request in your controller? Include $http in the parameters. Need to log to console? Include $log as your controller function argument.

What happens internally is this: Angular analyzes your function’s source code, finds the arguments, and infers from them the services your code requires.

Data Access

While Angular gives you complete freedom on how to structure your Model layer (you can use plain data variables, objects, and arrays in any combination), it provides a convenient way to talk to a REST API on the server. For example, here’s a way we might define and use the set of calls to retrieve and save User records.

Sure, there are ways to make jQuery code a shorter and clearer, and I’m sure most of my jQuery and Angular code could benefit from similar cleanup. But this is not a competition – who can do it in fewer lines of code – but rather a comparison of different approaches to DOM manipulation and data maintenance.

Great article. I’ve been trying to switch from the jQuery mindset myself and have been going through the excellent videos over on http://egghead.io.
Have you compared it to any other js framework out there? e.g. KnockoutJs?

Thanks Gavin! I haven’t worked with KnockoutJs myself, but as far as I know, there are a few more posts coming up on this blog, with similar comparisons between JS libraries and frameworks, based on personal experiences. Stay tuned!

Nice article. Another great thing readers should dig into is Angular routing and route parameters (http://docs.angularjs.org/api/ng.$route). It makes it so easy to understand the “flow” of an application as the routing cleanly shows the url/path and associated views (partials) and controller. There is also great support for promises (deferreds) with “q” (http://docs.angularjs.org/api/ng.$q) and bonus that you can have a resolve option for a view – so things that need to be done (load data etc.) can be done before the controller is instantiated and view loaded.

@GFoley83 – other frameworks, I played around with Backbone, Knockout but found Angular worked best for me.

I have experience with Adobe Flex and think Angular is what Flex should have been (using browser DOM, HTML, CSS as opposed to Flash runtime, MXML and own styling syntax – spark etc.) I believe Angular “founder” Misko is ex-Adobe.

Backbone – too much boilerplate for my liking and does a lot less than Angular.

Knockout – looked like it was aimed at Microsoft devs, seemed “dead” at the time. Since Angular has grown in popularity I get the impression Knockout has put significantly more effort in docs and promotion (I believe the developer is supported by or works for Microsoft – may be wrong).

[…] some parts of Angular that may be unexpected to a jQuery-trained brain in an earlier post, AngularJS for jQuery Developers. The best way to get free from jQuery reflexes in Angular projects is to avoid using jQuery […]

[…] javascript – How do I "think in AngularJS" if I have a jQuery background? – Stack Overflowhttp://blog.artlogic.com/2013/03…Embed QuoteComment Loading… • Just now Loading… require.enqueue(function(require) { […]

[…] AngularJS is a sweet web app framework. It comes with decent official documentation and samples, it looks superior among a large number of frameworks in an almost-real-world application test (the f… […]

[…] AngularJS is a sweet web app framework. It comes with decent official documentation and samples, it looks superior among a large number of frameworks in an almost-real-world application test (the famousTodoMVC project), and there are cool presentations and screencasts about it all over the web.But for a developer who has not used frameworks similar to Angular before, and has mostly worked withJavaScript libraries like jQuery, there may be some difficulty in shifting from the jQuery mindset to the Angular mindset. At least there was for me, and I’d like to share some notes–maybe this will be useful to someone.* Not a Library* Declarative, rather than Imperative* Two-way Data Binding* Dependency Injection* Data Access […]

[…] AngularJS is a sweet web app framework. It comes with decent official documentation and samples, it looks superior among a large number of frameworks in an almost-real-world application test (the famousTodoMVC project), and there are cool presentations and screencasts about it all over the web.But for a developer who has not used frameworks similar to Angular before, and has mostly worked withJavaScript libraries like jQuery, there may be some difficulty in shifting from the jQuery mindset to the Angular mindset. At least there was for me, and I’d like to share some notes–maybe this will be useful to someone.* Not a Library* Declarative, rather than Imperative* Two-way Data Binding* Dependency Injection* Data Access […]

[…] AngularJS is a sweet web app framework. It comes with decent official documentation and samples, it looks superior among a large number of frameworks in an almost-real-world application test (the famousTodoMVC project), and there are cool presentations and screencasts about it all over the web.But for a developer who has not used frameworks similar to Angular before, and has mostly worked withJavaScript libraries like jQuery, there may be some difficulty in shifting from the jQuery mindset to the Angular mindset. At least there was for me, and I’d like to share some notes–maybe this will be useful to someone.* Not a Library* Declarative, rather than Imperative* Two-way Data Binding* Dependency Injection* Data Access […]

What if you need to implement pixel perfect representations of a UI Design? Can you just plug in the CSS? How hard is it to transfer ui design interactions tested for usability and created in jquery? That will not come out of another departments processes, so is it harder to translate than start from scratch?

I really love AngularJS, even when I just stepped into it some days ago.
Still I don’t get why people claim jquery being the evil of all AngularJS projects.

I’d really like to know why I read everywhere that its so bad to manipulate the DOM with jquery while having AngularJS around.
To be honest, there is ton of stuff I can just do with jquery quicker/faster – without writing a directive for every little shit.

Talking about that jQuery example above, I’m not the best programmer, that goes for my jQuery knowledge too – but that example you’ve provided is horrible.
I know its not a competition, but ether use a real example or at least make a note that the example is a simulation of a worst case scenario with jQuery.

Art & Logic has been developing software on a work-for-hire basis since 1991. We have worked with over 900 clients in a diverse set of industries, including education, aerospace, music technology, consumer electronics, entertainment, financial services, and many more.

Copyright 1995–2015 Art & Logic, Inc. All rights reserved. All trademarks associated with the registered trademark "Art & Logic," including but not limited to "ArtLogic" and "artandlogic.com," are owned by Art & Logic, Inc. Terms of Use and Privacy Policy