Controllers - AngularJS

AngularJS supports Model-View-Controller (MVC) architecture pattern.

A Controller is a javascript object which has properties and functions.

AngularJS Controller is the only object that communicates with both Models and Views.

Controller Directive

In AngularJS application, a controller directive is defined with ng-controller directive.

<div ng-controller="empController">

Controller Syntax

	angular.module('empApp', []).controller('empController', ['$scope', function($scope)
		$ = '';
		$scope.getName = function() {
			$scope.greeting = 'Hello ' + $;
  • Create new module empApp using the angular.module function.
  • Create empController controller using the empApp module object.
  • Pass $scope as an argument to controller function. $scope is an object that refers to the application model.
  • Create name property on the controller object.
  • Create getName function on the controller object.

as Syntax

You can create alias for a controller using "as".

To use an alias with the controller, you must use "this" instead of $scope parameter.

<body ng-app="empApp">
	<div ng-controller="empController as mainCtrl">
		<span>{{ }}
	<script src="" ></script>
	angular.module('empApp', []).controller('empController', [function()
	{ = 'James';

Controller Inheritance

A controller can be nested into another controller.

A child controller can inherit properties and functions from their parent controller.

<body ng-app="empApp">
	<div ng-controller="mainCtrl">
		<p>{{ name }}</p>
		<p>{{ greeting() }}</p>
		<div ng-controller="empCtrl">
			<p>{{ name }} </p>
			<p>{{ Age }} </p>
			<p>{{ greeting() }} </p>
		<div ng-controller="mgrCtrl">
			<p>{{ name }} </p>
			<p>{{ position }} </p>
			<p>{{ greeting() }} </p>
	<script src="" ></script>
	var app = angular.module('empApp', []);
	//main controller
	app.controller('mainCtrl', ['$scope', function($scope){
		$ = 'James';
		$scope.greeting = function() {
			return "Hello " + name;
	//employee controller
	app.controller('empCtrl', ['$scope', function($scope) {
		$scope.age = 24;
	//manager controller
	app.controller('mgrCtrl',['$scope', function($scope) {
		$scope.position = 'manager';
  • Create three controller mainCtrl, empCtrl, mgrCtrl.
  • empCtrl and mgrCtrl are the child controllers of mainCtrl.
  • mainCtrl contains one property name and a single function greeting.
  • empCtrl inherit both name and greeting function from the mainCtrl.
  • mgrCtrl inherit both name and greeting function from the mainCtrl.
  • empCtrl introduce new property age.
  • mgrCtrl introduce new property position.

Join our newsletter and get an occasional email with a technology and news update.