Sunday, September 21, 2014

Discovering AngularJS

I've recently been pointed towards AngularJS by a mentor. At work, we typically use BackboneJS for our client-side framework needs. Since Backbone is so minimalist, over the past few years we've learned some (sometimes expensive) lessons and developed a set of best practices that minimize the pain of developing with Backbone.

The first thing I noticed when looking at Angular was how many of those implicit lessons and best practices become unnecessary! For example, it's not unusual for me to have to reimplement two-way binding for every application, and I've seen some complex mechanisms to do as-you-type filtering of a list. With Angular, it's so incredibly easy!

For example:

    <body>
        <div class="container" data-ng-controller="SomeController">
           
            <h3>Controllers</h3>
            Name: <input type="text" data-ng-model="nameFilter" />
            <ul>
                <li data-ng-repeat="person in people | filter:nameFilter">
                    {{person.name | uppercase}} loves {{person.city | uppercase}}
                </li>

            </ul>
        </div>
       
        <script type="text/javascript" src="js/libs/angular.min.js"></script>
        <script type="text/javascript" src="js/viewcontrollerscope.js"></script>
    </body>


And in the JS:

var demoApp = angular.module("demoApp", []);

var controllers = {};

controllers.SomeController =  function ($scope) {
    $scope.people = [
        { name: "Kim", city: "Green Bay" },
        { name: "Ron", city: "Miami" },
        { name: "Rufus", city: "Houston" },
        { name: "Wade", city: "San Francisco" }
    ];
};

demoApp.controller(controllers);



Boom! That's it. Most of that code is just boilerplate required to setup Angular itself, and one you do that, the filtering mechanism is handled within the bolded part of HTML template. Isn't that incredible?

I think I'm a little biased against Backbone because it was my first JS framework, and so the learning curve was obviously higher. However, I have to acknowledge, that Backbone is incredibly useful for adding small, clientside-driven pieces to an application. As far as I can tell, Angular seems much better oriented towards writing applications that are entirely clientside, single-page applications.

I highly recommend this tutorial for learning Angular. I found it incredibly useful. Let me know if you have any recommendations for Angular-related resources!


0 comments:

Post a Comment