Angular JS – How to create a Controller ?

Angular JS – How to create a Controller ?

Here I am going to show you the ways you can create a controller in Angular JS.

I am assuming, you already know the advantages of Angular JS and how to use Angular JS basics like ng-app, ng-controller, $scope.

Just to give you some basic idea on Angular JS, It is a Web Framework which would give you lot of flexibility and de-couple your Model-View-Controller with the client side code. This has been the most popular and critical feature of Angular. Lets try to get into the controller part. The controller is very important component in the MV* pattern which Angular talks about.

This controller can be created in 3 different ways which I would show you here.

Basic Way: (Controller as Global Function)  / app.js

This way is easy to create, perhaps this is not the best way to solve the problem. As this is a global function there could be many complications when we have multiple functions defined in the app. If the app grows bigger there is no way to isolate this function from others. So, this is not the way to go.

var app = angular.module("app", []);
var TestController = function($scope){
 $scope.count = 10;

2nd Way (Application level Controller)

This is application level controller defined as we are defining controller on app. Tomorrow we might need many other things at application level which might be included in the same controller. So, this is the angular way of doing it, still not the best practice. There could be modular way of doing it and adding as dependency to the application (app).

var app = angular.module("app", []);
app.controller('TestController', function($scope){
 $scope.count = 10;

3rd Way (Module level Controller)

Here we are defining another module which is a controllers and added this module as dependency to the app module. This way tomorrow if we want to add another controller we can simple add it to this module and it will be available in the application easily. If we don’t want the new controller exposed to the app then we can simply define another module. So, here is the best practice to create a controller in Angular.

var app = angular.module("app", ['controllers']);
angular.module("controllers", []).controller('TestController', function($scope){
 $scope.count = 10;

Note: To keep the simplicity, I have used a very basic example to show you the differences. You can use the same HTML given below to test all the three controllers. Put the controller code in app.js file.


<!DOCTYPE html>
<html ng-app="app">

<div ng-controller="TestController"> 

<script type="text/javascript" src="js/angular-min.js"></script>
<script type="text/javascript" src="app.js"></script>