Off the Ridge code

Off the Ridge Code Newsletter


How to Angular – Part 2 – Controllers in AngularJS

Published April 4, 2015 in AngularJS - 0Comments

Controllers in AngularJS

In the last post I’ve showed you how to create a ‘Hello World’ type of application in Angular. Now I’m going to introduce you to controllers and MVC.

Let’s start with defining MVC and what it is: MVC is an architectural pattern and it applies a principle of separation of concerns. In short, it divides our application into:

1. model – holds all of our data.

2. view – presents data to the user (our HTML page) and is in no way tied to the model. In other words, controller talks to the $scope object and never to the view.

3. controller – keeps view and model separated and is in charge of a particular area in our application. Controller is invoked by the Angular framework and builds up the model.

Screen Shot 2015-04-04 at 1.20.12 PM

The $scope object is supplied to our controller function by the Angular during controller invocation. By the way, anything with $ (dollar sign) in front is owned by the Angular framework.

<ng-controller> directive needs to be somewhere inside <ng-app> directive, and remember you can only have one <ng-app> per page, but many <ng-controller> directives (i.e. controllers.)

Before we can create a controller we need to create a module for our application. Then, we can create a controller and finally our model. Hence, there are 3 distinct steps when creating a module and registering controller:

1. Create a module:

var app = angular.module(‘myfirstangularapp’, []);

The first parameter is the name of our application, and the second parameter is an array of dependencies. (we don’t have any yet.)

2. Register controller with the module.

app.controller(“MyFirstController”, [“$scope”, MyFirstController]);

3. Instruct Angular to use our module.

<body ng-app=”myfirstangularapp”>

Now all that’s left is to create our controller function “MyFirstController”:

var MyFirstController = function ($scope) {


So how do we create a model?

We simply attach, or, in other words, assign properties to the $scope object and they become our model. e.g. $scope.myproperty or $scope.mycomplexobject.

var MyFirstController = function ($scope) {
$scope.ManyHellos = [‘Hello’, ‘Hola’, ‘Bonjour’, ‘Guten Tag’, ‘Ciao’, ‘Namaste’, ‘Yiasou’];

Here’s a complete example in JSFiddle:

(please not that <body ng-app=”myfirstangularapp”> is placed under ‘Fiddle Options’ Body Tag. I couldn’t get JSFiddle to work otherwise)

I hope you’ve enjoyed this post and, as always, please send me your comments and suggestions.