Code Smoothie

AngularJS Views

This post aims to describe “views” in Angular. It is targeted towards people who have a boilerplate understanding of Angular. I hope to be doing more tutorials about Angular.

My description of a view consists of a template, controller, and optionally, a custom directive.

The minimum

The template (the HTML source):

<div ng-controller="myCtrl">
  //controller accessible through entire block


angular.module('app', [])
  .controller('myCtrl', function() {
    //controller contents here

We have just attached a controller function named ‘myCtrl’ to the Angular module.

Role of a controller

The sole purpose of an Angular controller is provide the template with state and helper functions. It is not supposed to manipulate the DOM.

We will be using the ng-class and ng-click directives, as well as controller as syntax.

When using controller as, we treat the controller as a class, using dot notation.

Say we want a toggle button switches between 2 states when you click on it. Let’s walk through the code.

The controller function has three parts:

  1. A boolean variable to keep track of state. Note this is not exposed to the template, because we are not storing the state in this.

     var active = false;
  2. Helper function that tells us whether the button is active

     this.isActive = function () {
       return active;
  3. Helper function to toggle the state

     this.toggle = function () {
       active = !active;

Really simple, isn’t it? You may wonder if we need to encapsulate the active variable at all if the exposed functions are so simple. Doing so keeps the template simple and minimizes “work” in the template. It allows us to separate our concerns.

And the template:

(Styling is from Bootstrap, to keep it simple.)

<div ng-controller="toggleButtonCtrl as toggleBtn">
  <a href="#" ng-class="{'active': toggleBtn.isActive()}"
    My Btn

Things to note

  1. In our first line, we instantiate our controller, so we can access its properties using toggleBtn.myproperty.
  2. The attribute value of ng-class here is {'classtoApply': ifThisEvalsToTrue}. We apply the .active class only when our helper function returns true.
  3. The attribute value of ng-click is evaluated when it is clicked. It is essentially onclick but works with Angular stuff.

Working demo:

Shortly before posting this, I wrote a Stack Overflow answer related to this post.