archive / 2013

Six months of AngularJS: two-way binding is magic, until it isn't

What I've learned about AngularJS 1.0 after six months at the startup: how two-way binding and the digest cycle actually work, and the three gotchas that cost me the most time.

Six months ago I went from jQuery spaghetti at the agency to a codebase at the startup built on AngularJS. The first week felt like cheating. The second week I hit my first bug that I didn’t understand at all. Six months in, I think I finally get what’s happening under the hood, so let me write it down before I forget.

Everything below is AngularJS 1.0.8, which is what we run in production. The 1.2 release candidates look good, but Sarah, our CTO, has a rule: we don’t upgrade a framework the month it’s released. Jef would approve.

The magic#

Here’s the thing that sold me. A list of customers with a search box:

<div ng-app="crm" ng-controller="CustomerListCtrl">
    <input type="text" ng-model="search" placeholder="Search...">
    <p>{{ (customers | filter:search).length }} of {{ customers.length }} customers</p>

    <ul>
        <li ng-repeat="customer in customers | filter:search | orderBy:'name'">
            {{ customer.name }} ({{ customer.city }})
            <button ng-click="remove(customer)">Remove</button>
        </li>
    </ul>
</div>
angular.module('crm', [])
    .controller('CustomerListCtrl', ['$scope', '$http', function ($scope, $http) {
        $scope.customers = [];

        $http.get('/api/customers').success(function (data) {
            $scope.customers = data;
        });

        $scope.remove = function (customer) {
            var index = $scope.customers.indexOf(customer);
            $scope.customers.splice(index, 1);
        };
    }]);

No $('#list').empty(), no building <li> elements by hand, no keeping a counter in sync. You change the data, the view follows. Type in the search box, $scope.search changes, the list filters. That’s two-way binding: the input updates the model, the model updates the view.

The array syntax ['$scope', '$http', function ($scope, $http) {...}] looks redundant, but you need it. Angular figures out what to inject from the parameter names, and a minifier renames those to a and b. Without the array, your app works perfectly until the build step, and then nothing works at all. Ask me how I found out.

How it actually works: the digest cycle#

There’s no magic, of course. Angular doesn’t know when your data changes. It checks.

Every {{ }} and every ng-model registers a watcher on the scope: a function that returns a value, plus the last value it saw. When something happens that Angular knows about (a click via ng-click, an $http response, typing in an input), it starts a digest: it goes through all watchers and compares the current value with the previous one. If anything changed, it updates the DOM and goes round again, because one change may have triggered another. It stops when a full round finds nothing new, or gives up after ten rounds with an error.

That’s called dirty checking, and once you understand it, all three of my biggest bugs suddenly made sense.

Gotcha 1: changes outside Angular#

// doesn't update the view
setTimeout(function () {
    $scope.status = 'Saved';
}, 1000);

The value changes, but Angular doesn’t know, so no digest runs and the view stays the same. Until you click something else, and then suddenly “Saved” appears. Very confusing.

The fix is to tell Angular, or better, to use Angular’s own version:

// option 1: wrap it in $apply
setTimeout(function () {
    $scope.$apply(function () {
        $scope.status = 'Saved';
    });
}, 1000);

// option 2: inject $timeout and let Angular handle it
$timeout(function () {
    $scope.status = 'Saved';
}, 1000);

The same goes for jQuery plugins, WebSocket events from our Socket.IO connection and anything else that lives outside Angular. If the callback doesn’t come from Angular, you need $apply.

Gotcha 2: always put a dot in your ng-model#

This one is sneaky. Some directives, like ng-include and ng-repeat, create a child scope that inherits from the parent via JavaScript prototypes.

<div ng-controller="SettingsCtrl">
    <div ng-include="'partials/name-field.html'"></div>
    <p>Hello, {{ name }}</p>
</div>

If name-field.html contains <input ng-model="name">, typing in it creates a new name property on the child scope. The parent’s name never changes, so the greeting never updates. That’s just how prototypal inheritance works: reading goes up the chain, writing creates a property on the object itself.

The fix: bind to a property of an object instead.

$scope.user = { name: '' };
<input ng-model="user.name">
<p>Hello, {{ user.name }}</p>

Now the child scope reads user from the parent and writes to user.name on the same object. The rule of thumb in the Angular community is “if there’s no dot in your ng-model, you’re doing it wrong”, and after losing an afternoon on this, I agree.

Gotcha 3: too many watchers#

Dirty checking means every digest walks every watcher. With a few hundred that’s nothing. On our reporting page we had an ng-repeat showing a table of 500 rows with eight bound columns plus a few ng-class and ng-show per row. That’s well over 5,000 watchers, and every keystroke in the filter box triggered a digest. On the laptops of our customers, typing started to lag noticeably.

What helped:

  • Pagination. Nobody reads 500 rows. We show 50 now.
  • Fewer bindings per row. Some columns were computed in the template with filters. We now compute them once when the data comes in.
  • Don’t filter on every keystroke. We debounce the search input with $timeout, so the filtering only kicks in after the user stops typing for 300 ms.

A colleague added a little snippet to our debug toolbar that counts the watchers on the page. It’s a sobering number.

So, is it worth it?#

Yes. Our frontend code is a fraction of what the same thing would be in jQuery, and it’s actually testable, which I can’t say about anything I wrote at the agency. But “it just works” only lasts until it doesn’t, and then you need to know about scopes, watchers and digests. The magic is a lot less scary once you know it’s a loop with an if in it.

Next up: I want to write my own directives without copying them from a blog. Report to follow.

    Tip: / opens search, ↑↓ to select, ↵ to open.