Dynamic HTML and the browser wars → Two-way binding (AngularJS)
1995 – today · 2010 – 2021
What changed
- Where the state lives
Dynamic HTML and the browser wars
In the page: a JavaScript array and a filter variable. Nothing is saved; a reload starts again from the code.
Two-way binding (AngularJS)
On
$scope: plain objects in$scope.todos, the filter in$scope.showand the text field's value in$scope.newTitle.- How the page is rendered
Dynamic HTML and the browser wars
render()builds the whole list as one HTML string and swaps it in withinnerHTML.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
Dynamic HTML and the browser wars
Handler attributes (
onsubmit,onclick) call global functions that change the array and callrender().Two-way binding (AngularJS)
Directives run handlers inside
$apply; the digest evaluates every watcher again and changes the DOM where a value differs.ng-modelalso writes from the field back to the scope.- How the code is organised
Dynamic HTML and the browser wars
One script of global functions, wired to the page by attributes in the HTML. No server is involved.
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.
Dynamic HTML and the browser wars→AJAX
The page could change itself, but it could not exchange data with the server without leaving: loading fresh data or saving a change still meant a form submission or a link and a whole new page, and everything kept in variables was gone after it. On top of that, every browser needed its own branch of the code. XMLHttpRequest and the AJAX approach let a script talk to the server in the background and update only the part of the page that changed.
AJAX→jQuery
Every browser did it a little differently. Internet Explorer 5 and 6 created the object with
new ActiveXObject("Microsoft.XMLHTTP"), Internet Explorer before version 9 attached events withattachEventinstead ofaddEventListener, and each browser had its own DOM quirks, so scripts grew long and full of browser checks. Libraries like jQuery wrapped XHR, events and the DOM in one short API that worked the same in every browser.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.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.
Dynamic HTML and the browser wars
plain browser APIs, no library
/src/main.js · 73 lines
// DHTML era: the page changes itself in the browser. The list is a JavaScript array, and
// render() writes it into the page as one HTML string. No server is asked.
// The state is plain variables in the page: a reload starts again from these lines.
var todos = [
{ id: 1, title: "Read the docs", done: true },
{ id: 2, title: "Write the app", done: false }
];
var nextId = 3;
var filter = "all";
var FILTERS = ["all", "active", "done"];
// The text the user typed becomes part of the HTML, so it is escaped first.
function escapeHtml(text) {
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
}
function render() {
var html = "";
var left = 0;
var i, todo;
for (i = 0; i < todos.length; i++) {
todo = todos[i];
if (!todo.done) left++;
if (filter == "all" || (filter == "done") == todo.done) {
// The handler is part of the string: onclick calls a global function with the id.
html += '<li' + (todo.done ? ' class="done"' : '') + '><label>' +
'<input type="checkbox" data-toggle onclick="toggleTodo(' + todo.id + ')"' +
(todo.done ? ' checked' : '') + '> ' +
'<span class="title">' + escapeHtml(todo.title) + '</span></label></li>';
}
}
// innerHTML throws the old items away and builds new ones, so a focused checkbox loses focus.
document.getElementById("todo-list").innerHTML = html;
document.getElementById("todo-count").innerHTML = left + " left";
for (i = 0; i < FILTERS.length; i++) {
document.getElementById("filter-" + FILTERS[i]).className = FILTERS[i] == filter ? "selected" : "";
}
}
function addTodo() {
var field = document.getElementById("new-todo");
var title = field.value.replace(/^\s+|\s+$/g, "");
if (title != "") {
todos.push({ id: nextId++, title: title, done: false });
field.value = "";
render();
}
// false cancels what the browser would do next: send the form and load a new page.
return false;
}
function toggleTodo(id) {
for (var i = 0; i < todos.length; i++) {
if (todos[i].id == id) todos[i].done = !todos[i].done;
}
render();
}
function setFilter(name) {
filter = name;
render();
}
// A <script> of the time ran in the global scope: every function above became global, and
// the onclick attributes could call it. The lab runs each file as a module with its own
// scope, so the functions the markup calls are put on window by hand.
window.addTodo = addTodo;
window.toggleTodo = toggleTodo;
window.setFilter = setFilter;
// Like a <script> at the end of <body>, this runs when the elements already exist: draw the list.
render();Two-way binding (AngularJS)
AngularJS 1.8.3
/index.html · 35 lines
<!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>