Stay ahead and focused

Language of Web

Sep 7

HTML and Angular

Who does not like small visual clues when you hover your mouse over something. We add interactions like this everyday using Javascript. But sometimes we feel lost the ownership for that action due to the laundry list way of writing our code.


Take the following HTML code as an example,

    <h1 id="title">Web Technology</h1>

In order to change the title, we can write the following code and put it anywhere.

    $(function() {
        var title = "Web Languages";
        // use jQuery library to access DOM element

There's not easy way to find which HTML element we are working on without scanning over all the HTML templates afterwards. For some project this task can involve thousand of lines scattered around quite many files and folders. Not to mention sometimes we couple the look with the business logic code so that in the end there's no obvious re-usability that can come out of it.


Luckily, there's an old discipline that originated back from 1970, exploded in popularity in web industry from their success in desktop computing. It is the model-view-controller design pattern, MVC. Basically it splits the responsibility of a complex interactive problem into three components, and let each component do their own thing eliminating tangling between data, interaction and look at early stage.

AngularJS is one of the Javascript framework providing MVC architecture designed for rich internet applications. For instance, given same HTML, we can claim ownership as well as attaching Javascript variables to HTML elements via attributes.

  <div ng-controller="Ctrl">
      <h1 ng-model="title">Web Technology</h1>
          <li ng-repeat="item in list"></li> 

The HTML code is now controlled by a controller Ctrl and contains two references to variables title and list. The class and variables are defined in a module unit in the following.

    // module design with dependency injection
    .module('app', ['...'])
    // group functions by controller    
    .controller('Ctrl', function ($scope) {
        $scope.title = 'Web Languages';
        $scope.list = ['HTML', 'Javascript', 'CSS'];

The code written with or without MVC approach is comparable in most of the cases. But you can see the former gives better architecture structure for how and where you should store the files and what is the responsibility of each file (or module).

What's interesting about AngularJS is that the architect does not pick a pre-wired folder structure for you. What it provides is the way to help you organize your code into modular design, which happens to be very important, especially for large enterprise applications requiring decent amount of re-usability and scalability.


  1. AngularJS — Superheroic JavaScript MVW Framework