Skip to content
FrontDepth, Home

jQuery → Two-way binding (AngularJS)

2006 – today · 2010 – 2021

Older era
Newer era
Compare

What changed

Where the state lives

jQuery

In the DOM: a todo is done when its <li> has the class done, and the counter is found by counting elements.

Two-way binding (AngularJS)

On $scope: plain objects in $scope.todos, the filter in $scope.show and the text field's value in $scope.newTitle.

How the page is rendered

jQuery

The server sends the first HTML. New items are built with $("<li>") and appended.

Two-way binding (AngularJS)

The HTML is the template: AngularJS compiles the ng-* attributes and {{ }} once, then each binding updates its own piece of the DOM.

What happens on a change

jQuery

Each handler changes the elements it knows about, then refresh() fixes the counter and the filter.

Two-way binding (AngularJS)

Directives run handlers inside $apply; the digest evaluates every watcher again and changes the DOM where a value differs. ng-model also writes from the field back to the scope.

How the code is organised

jQuery

One script of event handlers. A delegated handler on #todo-list also covers items added later.

Two-way binding (AngularJS)

A module, a controller that fills $scope, and directives in the HTML. The controller has no DOM code.

Why it changed

What hurt in each era along the way, and the era that came next.

  1. jQuery→MVC in the browser (Backbone)

    When the data lives only in the DOM, every feature reads and writes the page directly: the counter counts <li> elements, the filter checks classes. As apps grew, handlers changing the page from many places became hard to follow ("jQuery spaghetti"), and there was no model of the data to test, save or reuse. Libraries like Backbone moved the data into models and kept the page in views.

  2. MVC in the browser (Backbone)→Two-way binding (AngularJS)

    Backbone left the wiring to you. Every view subscribed to its models by hand, chose what to redraw and read form fields back itself, so much of the code only connected data to the DOM. A view thrown away without remove() stayed subscribed and kept reacting as a "zombie view", and re-rendering a template replaced elements, losing focus and half-typed text. AngularJS answered with two-way data binding: the HTML declares what shows what, and the framework keeps the page and the data in sync.

The same app, side by side

The main file of each version. Both apps pass the same test: same markup, same behaviour, different ideas.

The apps run in sandboxes in your browser.

jQuery
Two-way binding (AngularJS)

jQuery

jQuery 4.0.0

/src/main.js · 52 lines

JavaScript
// jQuery era: the page itself is the state. Handlers read the DOM, change it, recount.
import $ from "jquery";

// $(fn) waits until the document is ready, like $(document).ready(fn).
$(function () {
  let filter = "all";

  // Brings the counter, the visible items and the filter buttons in line with the DOM.
  function refresh() {
    const left = $("#todo-list li").not(".done").length;
    $("#todo-count").text(left + " left");

    $("#todo-list li").each(function () {
      const done = $(this).hasClass("done");
      $(this).toggle(filter === "all" || (filter === "done") === done);
    });

    $("[data-filter]").removeClass("selected");
    $('[data-filter="' + filter + '"]').addClass("selected");
  }

  $("#todo-form").on("submit", function (event) {
    event.preventDefault();
    const title = String($("#new-todo").val()).trim();
    if (!title) return;

    // Build the new <li> the same way the server wrote the first ones.
    const $item = $("<li>").append(
      $("<label>").append(
        $('<input type="checkbox" data-toggle>'),
        " ",
        $('<span class="title">').text(title),
      ),
    );
    $("#todo-list").append($item);
    $("#new-todo").val("");
    refresh();
  });

  // One delegated handler on the list also covers the items added later.
  $("#todo-list").on("change", "[data-toggle]", function () {
    $(this).closest("li").toggleClass("done", this.checked);
    refresh();
  });

  $(".filters").on("click", "[data-filter]", function () {
    filter = $(this).data("filter");
    refresh();
  });

  refresh();
});

Two-way binding (AngularJS)

AngularJS 1.8.3

/index.html · 35 lines

HTML
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Todos · AngularJS</title>
    <link rel="stylesheet" href="/styles.css" />
  </head>
  <body>
    <!-- The page is the template: ng-* attributes and {{ }} bind it to TodoCtrl's $scope. -->
    <main class="todo-app" ng-controller="TodoCtrl">
      <h1>Todos</h1>
      <!-- A form without an action: AngularJS stops the real submit and calls add(). -->
      <form id="todo-form" ng-submit="add()">
        <!-- Two-way: typing writes $scope.newTitle, and setting newTitle changes the field. -->
        <input id="new-todo" ng-model="newTitle" placeholder="What needs doing?" autocomplete="off" aria-label="New todo" />
        <button id="add" type="submit">Add</button>
      </form>
      <ul id="todo-list">
        <!-- ng-repeat gives every <li> a child scope holding its todo. ng-model="todo.done" writes -->
        <!-- straight into that object, so the controller's list sees the change. -->
        <li ng-repeat="todo in todos | filter:matches" ng-class="{done: todo.done}">
          <label><input type="checkbox" data-toggle ng-model="todo.done" /> <span class="title">{{todo.title}}</span></label>
        </li>
      </ul>
      <div class="footer">
        <span id="todo-count">{{remaining()}} left</span>
        <div class="filters">
          <button type="button" data-filter="all" ng-class="{selected: show == 'all'}" ng-click="show = 'all'">All</button>
          <button type="button" data-filter="active" ng-class="{selected: show == 'active'}" ng-click="show = 'active'">Active</button>
          <button type="button" data-filter="done" ng-class="{selected: show == 'done'}" ng-click="show = 'done'">Done</button>
        </div>
      </div>
    </main>
  </body>
</html>