jQuery versus Angular: Tweet

I’ve been asked what is the role of AngularJS and how does it fit with jQuery. Instead of a long explanation I thought some code samples can help in understanding some of the the differences.

Below are two code samples, one in jQuery and one in Angular. The code displays how close you are to the 140 character limit in Tweeter. This is what it looks like:

jquery-angulary-mockup-1
As you type the message updates to tell you how many characters are left. Once you’ve type 120 characters the message turns orange. Like this:

jquery-angulary-mockup-2
This is what the code looks like if you did this using jQuery: http://jsfiddle.net/luisperezphd/XGW25/

<!DOCTYPE html>
<html>
<head>
    <script src="jquery-2.0.3.min.js"></script>
    <style>
    .warning {
        color: orange;
    }
    </style>
    <script>
        $(function() {
            function updateCharCount() {
                var tweet = $("#tweet").val();
                $("#tweetCharsLeft").text(140 - tweet.length);

                if(tweet.length > 120) {
                    $("#tweetCharMsg").addClass("warning");
                } else {
                    $("#tweetCharMsg").removeClass("warning");
                }
            }

            updateCharCount();

            $("#tweet").on("keyup", function() {
                updateCharCount();
            });
        });
    </script>
</head>
<body>
    <input id="tweet" />
    <span id="tweetCharMsg">
        <span id="tweetCharsLeft"></span> characters left
    </span>
</body>
</html>

And this is what the same functionality looks like in AngularJS:
http://jsfiddle.net/luisperezphd/u9DtC/

<!DOCTYPE html>
<html ng-app>
<head>
    <script src="angular.min.js"></script>
    <style>
    .warning {
        color: orange;
    }
    </style>
</head>
<body>
    <input ng-model="tweet" />
    <span ng-class="{ warning: tweet.length > 120 }">
        {{140 - tweet.length}} characters left
    </span>
</body>
</html>

If you like what you’ve read sign up for my mailing list.

Leave a Reply

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