← Blog Home

AngularJS for jQuery Developers

34 Replies.

AngularJS-large

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.Angular MVC

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:

<input id="toggleShowHide" type="checkbox"><div id=”specialParagraph”>
    This content will disappear and reappear if you click the checkbox above
</div><script>
    $(function() {
         function toggle() {
            var isChecked = $('#toggleShowHide').is(':checked');
            var specialParagraph = $('#specialParagraph');
            if (isChecked) {
                specialParagraph.show();
            } else {
                specialParagraph.hide();
            }
        }
        $('#toggleShowHide').change(function() {
            toggle();
        });
        toggle();
    });
</script>

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.

<input type="text" ng-model="yourName" placeholder="Enter a name here" />
<h1>Hello {{yourName}}!</h1>

Live version: http://jsfiddle.net/6UnVA/1/

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.

var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
  user.abc = true;
  user.$save();
});

Angular predefines reasonable defaults for getting, setting, deleting, and querying records. And parametrized URLs give you the ability to customize data access to your needs.

Other things that deserve to be mentioned but weren’t are form validation, unit testing, and angular-ui library. Perhaps in a future post.

See also: I’ve Been Doing It Wrong!

 

(Image from http://angularjs.org/)

34 thoughts on “AngularJS for jQuery Developers”.

  • Your jQuery code is unnecessarily verbose and adds more flow control than is needed. A much more succinct way would be

    $(“#toggleShowHide”).change(function() {
    $(“#specialParagraph”).toggle($(this).prop(“checked”));
    });

    Mind you, I’d rather write an Angular app than a jQuery application, but I’d also rather show why using more fair examples!

    • You’re completely missing the point; he was demonstrating how convoluted jQuery code can be and how AngularJS removes the dependency on jQuery to manipulate the DOM.

    • Vlad Orlenko says:

      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.

      • bob says:

        Still that was a fair and valid point. It’s misleading people into thinking verbosity is the issue. Thanks Petter for providing a more meaningful jquery example.

  • 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?

    • Vlad Orlenko says:

      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!

  • Thanks for this post, very useful for those of us used to jQuery, very nice.

    Wanted to point out a couple of typhos I found:

    var isChecked = $(‘#toggleShowHide).is(‘:checked’); // missing: ‘

    … data in scopes, functionality in controllesr, // “controllesr”

    Hope to see your next posts on the subject, thanks again!

  • Larry Battle says:

    Great article. However your jquery example is missing a closing quote for `toggleShowHide`.
    Also you can write it like this.

    Demo: http://jsfiddle.net/sPGdP/

    Rewritten jQuery

    	$(function () {
    		$('#toggleShowHide').change(function () {
    			$('#specialParagraph').toggle(this.checked);
    		}).trigger('change');
    	});
    

  • Jesus people, what’s with all the trolling? Chill out ay!

  • Johan says:

    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.

  • Johan says:

    @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).

    Worth checking out Addy Osmani’s TODO MVC for a “sample” of each framework (http://addyosmani.github.com/todomvc/) and then pick the one that works for you.

    • Phil says:

      I agree Angular is very similar to the approach Flex took and I didn’t really understand the Flex approach until I worked in ASP.NET. I would say all 3 have very similar flows/thoughts on structure.

  • Maddy says:

    The biggest problem with using google products is that they can cancel it anytime.

  • [...] AngularJS for jQuery Developers [...]

  • [...] http://blog.artlogic.com/2013/03/06/angularjs-for-jquery-developers/ and http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background - If you are a web developer, you have undoubtedly used jQuery. If you are looking to start using AngularJS, you need to start thinking differently about how you manipulate your DOM.  Angular has some great support for this but if you try to build things the jQuery way, you'll quickly lose the benefits provided by AngularJS. [...]

  • [...] Also see: AngularJS for jQuery Developers [...]

  • [...] 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 [...]

  • […] are couple of links explaining AngularJS to jQuery developers and my effort also goes to do the same. This post is dedicated to all the jQuery developers who […]

  • […] AngularJS for jQuery Developers […]

  • […] 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  […]

  • […] Art & Logic blog: AngularJS for jQuery Developers […]

  • madpixl says:

    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?

  • Matt says:

    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.

    For other peope:
    $(‘#toggleShowHide’).change(function (e) {
    $(‘#specialParagraph’).toggle(e.checked)
    });

  • Leave a Reply

    Follow Art & Logic on Twitter

    Follow Our Blog via RSS

    RSS

    Connect Socially

    A&L on Facebook

    A&L on Google+

    Home   About   Blog   Careers   Contact

    %d bloggers like this: