---
description: In this tutorial, we will learn What are Controllers in AngularJS, How it Works, and How to Build a Controller in AngularJS with ng-controller Example.
title: AngularJS Controllers with ng-Controller Example
image: https://www.guru99.com/images/angularjs-controllers-with-ng-controller.png
---

[Skip to content](#main)

**⚡ Smart Summary**

A Controller in AngularJS holds the business logic of a screen. It receives data through the scope object, processes it, and exposes the result back to the view, keeping presentation markup free of application logic.

- 🎯 **Core Responsibility:** A controller populates the scope object and exposes methods to the view; it does not manipulate the DOM.
- 🔗 **Wiring:** The ng-controller directive binds a named controller to an element, giving that element and its children access to the controller scope.
- 🔁 **Two-Way Binding:** ng-model links a form field to a scope property, so edits in the view update the controller and the reverse.
- 🧩 **Methods:** Functions attached to the scope separate distinct pieces of logic and are callable directly from view expressions.
- 🏷️ **controllerAs Syntax:** Aliasing a controller and binding to `this` removes ambiguity when controllers are nested inside one another.
- 📁 **Separation:** Moving controllers into a dedicated app.js keeps the view layer independent of the logic layer.

Read More

![AngularJS Controllers with ng-controller](https://www.guru99.com/images/angularjs-controllers-with-ng-controller.png)

## What is Controller in AngularJS?

A **Controller** in AngularJS takes the data from the View, processes the data, and then sends that data across to the view which is displayed to the end user. The Controller holds your core business logic. It uses the data model, carries out the required processing, and then passes the output to the view.

⚠️ **Version note:** AngularJS (the 1.x branch) reached end of life on 31 December 2021 and receives no further security patches. The concepts below still apply to legacy applications; in modern Angular the same role is filled by a component class rather than a controller.

Knowing what a controller is leaves one question open: how it actually communicates with the view. The next section answers that.

## What Controller does from Angular’s Perspective

Following is a simple definition of the working of an AngularJS Controller:

[![Working of AngularJS Controller]()](https://www.guru99.com/images/AngularJS/010416_0650_AngularJSCo1.png)

*Working of AngularJS Controller*

- The controller’s primary responsibility is to control the data which gets passed to the view. The scope and the view have two-way communication.
- View properties and events can call functions on the scope. The snippet below shows the [function($scope)](https://www.guru99.com/angularjs-scope.html) declared with the controller plus an internal function returning `$scope.firstName` and `$scope.lastName` joined. In [AngularJS](https://www.guru99.com/angularjs-introduction.html), a function defined as a variable is a Method.

[![Working of AngularJS Controller]()](https://www.guru99.com/images/AngularJS/010416_0650_AngularJSCo2.png)

- Data passes from the controller to the scope, and then back and forth between the scope and the view.
- The scope exposes the model to the view. The model can be modified via methods defined on the scope, which are triggered by events from the view.
- Controllers should not be used for manipulating the DOM. That is the job of [directives](https://www.guru99.com/angularjs-directive.html).
- Best practice is to base controllers on functionality. If you have an input form that needs a controller, create one called “form controller”.

With the mechanism understood, the next section builds a controller from an empty page.

## How to Build a Basic Controller in AngularJS

Below are the steps to create a controller in AngularJS.

**Step 1) Create a basic HTML Page**

Before creating a controller, the basic HTML page has to be in place. The snippet below is a simple page titled “Event Registration” that references Bootstrap and AngularJS.

[![Build a Basic Controller in AngularJS]()](https://www.guru99.com/images/AngularJS/010416_0650_AngularJSCo3.png)

1. References to the Bootstrap CSS stylesheet, used together with the Bootstrap library.
2. A reference to the AngularJS library. Everything done with AngularJS from here on is resolved from this file.
3. A reference to the Bootstrap library, which makes certain controls responsive.

⚠️ **Correction:** the original loaded jQuery and stated that AngularJS depends on it. It does not. AngularJS ships with jqLite, a built-in subset of the jQuery API, and only upgrades to full jQuery if jQuery loads *before* it. The reference has been removed.

**Step 2) Check the files and file structure**

[![Build a Basic Controller in AngularJS]()](https://www.guru99.com/images/AngularJS/010416_0650_AngularJSCo4.png)

1. Files are split into two folders as in any conventional web application: “css” for stylesheets and “lib” for [JavaScript](https://www.guru99.com/interactive-javascript-tutorials.html) files.
2. bootstrap.css sits in the css folder and gives the site its look and feel.
3. angular.js is the main library, downloaded from the AngularJS site and kept in lib.
4. app.js will contain the code for the controllers.

**Step 3) Use AngularJS code to display the output**

The goal here is to display the words “AngularJS” both as plain text and inside a text box when the page is opened in the browser.

[![Build a Basic Controller in AngularJS]()](https://www.guru99.com/images/AngularJS/010416_0650_AngularJSCo5.png)

```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Event Registration</title>
<link rel="stylesheet" href="css/bootstrap.css">
</head>
<body>
<h1> Guru99 Global Event</h1>

<div ng-app="DemoApp" ng-controller="DemoController">
Tutorial Name : <input type="text" ng-model="tutorialName"><br>
This tutorial is {{tutorialName}}
</div>

<script src="lib/angular.js"></script>
<script>
var app = angular.module('DemoApp', []);

app.controller('DemoController', ['$scope', function($scope) {
  $scope.tutorialName = "AngularJS";
}]);
</script>
</body>
</html>
```

**Code Explanation:**

1. **ng-app** marks this element as the root of an AngularJS application. Attributes prefixed with **ng-** are built-in directives. “DemoApp” is the name given to the application.
2. The div carries **ng-controller** with the name “DemoController”, which gives that element and everything inside it access to the controller scope.
3. **ng-model** creates the model binding, tying the Tutorial Name text box to the scope property `tutorialName`.
4. The module `DemoApp` is created, and the controller assigns a default value of “AngularJS” to `tutorialName`.

⚠️ **Corrections applied.** The original listing declared `chrset="UTF 8"`, which is neither a valid attribute nor a valid encoding name, and loaded AngularJS twice — once from the CDN and once from `lib/angular.js`. Loading the library twice re-registers the module system and produces unpredictable behaviour. The dependency array annotation `['$scope', function($scope){…}]` was also added, without which the controller breaks the moment the file is minified.

**Output:**

[![Build a Basic Controller in AngularJS]()](https://www.guru99.com/images/AngularJS/010416_0650_AngularJSCo6.png)

Because `tutorialName` was assigned the value “AngularJS”, that value appears in the text box and in the plain text line. A single property is enough for a demonstration; real controllers usually expose behaviour as well, which the next section covers.

**Don't Miss:**

- [What is AngularJS? Architecture, Features & Advantages](https://www.guru99.com/angularjs-introduction.html)
- [AngularJS Hello World: Your First Example Program](https://www.guru99.com/angularjs-first-program.html)
- [AngularJS Form Validation on Submit: $dirty, $valid & $invalid](https://www.guru99.com/angularjs-validation.html)
- [AngularJS Custom Directive: Templates, Scope & Transclude](https://www.guru99.com/angularjs-custom-directive.html)

## How to Define Methods in AngularJS Controllers

Normally one would define multiple methods in a controller to separate the business logic. If the controller had to add two numbers and subtract two numbers, you would create one method for each operation.

The example below defines a custom method inside an AngularJS controller that returns a string.

[![Define Methods in AngularJS Controllers]()](https://www.guru99.com/images/AngularJS/010416_0650_AngularJSCo7.png)

```
<!-- The head and library references are unchanged from Step 3 -->
<div ng-app="DemoApp" ng-controller="DemoController">
Tutorial Name : <input type="text" ng-model="tutorialName"><br>
This tutorial is {{tName()}}
</div>

<script>
var app = angular.module('DemoApp', []);

app.controller('DemoController', ['$scope', function($scope) {
  $scope.tutorialName = "AngularJS";

  // A method on the scope, callable from the view as tName()
  $scope.tName = function() {
    return $scope.tutorialName;
  };
}]);
</script>
```

**Code Explanation:**

1. A function is attached to the scope object as the member `tName`. It returns the current value of `tutorialName`.
2. The view calls the method with `{{tName()}}`. The parentheses matter: without them the expression prints the function itself rather than its result.

⚠️ **Correction:** the original method read `$scope.tName = function() { return $scope.tName; };`. That function returns itself, not the tutorial name, so the page rendered a function body instead of text. It now returns `$scope.tutorialName`.

**Output:**

[![Define Methods in AngularJS Controllers]()](https://www.guru99.com/images/AngularJS/010416_0650_AngularJSCo8.png)

So far everything has lived in one file. Production applications keep controllers separate, which is what the next section demonstrates.

## AngularJS Controller with ng-Controller Example

The “HelloWorld” example above placed all functionality in a single file. It is now time to move the controller code into its own file.

**Step 1)** In the app.js file, add the following code for your controller.

[![AngularJS Controller with ng-Controller]()](https://www.guru99.com/images/AngularJS/010416_0650_AngularJSCo9.png)

```
angular.module('app', [])
  .controller('HelloWorldCtrl', ['$scope', function($scope) {
    $scope.message = "Hello World";
  }]);
```

The above code does the following:

1. Defines a module called “app” which holds the controller.
2. Creates a controller named “HelloWorldCtrl” that displays a “Hello World” message.
3. Uses the scope object to pass information from the controller to the view, in this case a variable called `message`.

**Step 2)** In Sample.html, add a div carrying the ng-controller directive and a reference to the member variable `message`. Remember to reference app.js, which holds the controller source.

[![AngularJS Controller with ng-Controller]()](https://www.guru99.com/images/AngularJS/010416_0650_AngularJSCo10.png)

```
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title>Event Registration</title>
<link rel="stylesheet" href="css/bootstrap.css">
</head>
<body>
<h1> Guru99 Global Event</h1>
<div class="container">
<div ng-controller="HelloWorldCtrl">{{message}}</div>
</div>

<script src="lib/angular.js"></script>
<script src="app.js"></script>
</body>
</html>
```

⚠️ **Correction:** app.js must be loaded *after* angular.js, since it calls `angular.module`. The original also loaded the library twice and carried the same `chrset` typo.

**Output:**

[![AngularJS Controller with ng-Controller]()](https://www.guru99.com/images/AngularJS/010416_0650_AngularJSCo11.png)

Every example so far has read and written properties directly on `$scope`. The section below covers the alternative that the AngularJS team recommends instead.

## How to Use the controllerAs Syntax in AngularJS

Binding directly to `$scope` works, but it becomes ambiguous as soon as controllers are nested. A view expression such as `{{name}}` gives no clue which controller owns `name`, and because child scopes inherit from parent scopes prototypally, a nested controller that writes to an inherited primitive silently creates its own shadow copy. The `controllerAs` syntax removes both problems by giving each controller an alias.

**Step 1)** Alias the controller in the view using the `as` keyword, then prefix every binding with that alias.

**Step 2)** Inside the controller, attach properties to `this` rather than to `$scope`.

```
<div ng-controller="DemoController as demo">
Tutorial Name : <input type="text" ng-model="demo.tutorialName">
This tutorial is {{demo.tutorialName}}
</div>

<script>
app.controller('DemoController', function() {
  // 'vm' is captured so nested functions keep the right reference
  var vm = this;
  vm.tutorialName = "AngularJS";

  vm.tName = function() {
    return vm.tutorialName;
  };
});
</script>
```

Three gains follow. Bindings become self-documenting, because `demo.tutorialName` names its owner. Nested controllers stop colliding, since a parent aliased `outer` and a child aliased `inner` can both expose `name`. Values also bind through an object rather than a bare primitive, sidestepping the trap where an edit in a child never reaches the parent.

💡 **Tip:** Capture `this` into a variable such as `vm` at the top of the controller. Inside a callback, `this` refers to something else entirely, and the captured reference keeps the binding correct.

Choosing a binding style is one decision. Deciding what belongs in a controller at all is another, and the comparison below draws that line.

## Controller vs Service in AngularJS

Beginners frequently overload the controller with work that belongs in a service. The distinction is lifespan and reuse: a controller exists only while its view is on screen, whereas a service is a singleton that lives for the life of the application.

| Aspect | Controller | Service |
| --- | --- | --- |
| Lifetime | Created and destroyed with the view | Single instance for the whole application |
| Purpose | Prepare data for one view | Shared logic, state and server calls |
| Reusable | No, tied to its view | Yes, injectable anywhere |
| Holds state between views | No, state is lost on navigation | Yes, state persists |
| Typical content | Scope properties and view methods | HTTP calls, caching, business rules |

Keep controllers thin. If two controllers need the same logic, or if a value must survive navigation between views, move it into a service and inject that service where it is needed. A practical test is to ask whether the code would still make sense with the current screen closed. If the answer is yes, it belongs in a service.

## FAQs

🧭 Can the same controller be attached to more than one element?

Yes. AngularJS creates a separate instance and a separate scope for every element carrying the directive. The instances share no state, so a change in one does not appear in the other.

🛣️ When should a controller be declared in a route instead of ng-controller?

Declare it in the route when the controller belongs to a whole view loaded by [routing](https://www.guru99.com/angularjs-routes.html). Use ng-controller for a component that appears inside a page regardless of the current route. Never declare both, or the controller runs twice.

🔌 How do I stop dependency injection breaking after minification?

Use the array annotation, listing dependency names as strings before the function. Minifiers rename function arguments but never string literals, so the injector still resolves $scope and any services correctly.

🤖 Can AI generate an AngularJS controller from a description?

Yes. [AI](https://www.guru99.com/ai-tutorial.html) assistants produce the module, controller and scope bindings from a plain description of the screen. Always check the dependency annotation, since generated code often omits it.

🧠 How does AI help migrate $scope controllers to controllerAs?

AI tools rewrite scope assignments as properties on a captured vm variable and prefix every matching view binding with the alias. Review $watch calls and event listeners by hand, because those still require the scope object.

#### Summarize this post with:

ChatGPTPerplexityGrokGoogle AI

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.**

##### Sign up for the newsletter

Subscribe for Free

You have successfully subscribed.  
Please check your inbox.

![AI-Newsletter]() Chosen by over **350,000+** professionals

[Scroll to top](#wrapper)

×

Search for:

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/angularjs-controllers-with-ng-controller.png","url":"https://www.guru99.com/images/angularjs-controllers-with-ng-controller.png","width":"700","height":"250","caption":"AngularJS Controllers with ng-Controller","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/angularjs-controller.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/angularjs","name":"AngularJS"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/angularjs-controller.html","name":"AngularJS Controllers with ng-Controller Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/angularjs-controller.html#webpage","url":"https://www.guru99.com/angularjs-controller.html","name":"AngularJS Controllers with ng-Controller Example","dateModified":"2026-10-08T17:58:01+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/angularjs-controllers-with-ng-controller.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/angularjs-controller.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/editorial","name":"Editorial Team","url":"https://www.guru99.com/author/editorial","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/favicon-new-logo.png","url":"https://www.guru99.com/images/favicon-new-logo.png","caption":"Editorial Team","inLanguage":"en-US"},"sameAs":["https://www.guru99.com/editorial-team"],"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"AngularJS","headline":"AngularJS Controllers with ng-Controller Example","description":"In this tutorial, we will learn What are Controllers in AngularJS, How it Works, and How to Build a Controller in AngularJS with ng-controller Example.","keywords":"angularjs","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/editorial","name":"Editorial Team"},"dateModified":"2026-10-08T17:58:01+05:30","image":{"@id":"https://www.guru99.com/images/angularjs-controllers-with-ng-controller.png"},"copyrightYear":"2026","name":"AngularJS Controllers with ng-Controller Example","subjectOf":[{"@type":"HowTo","name":"How to Build a Basic Controller in AngularJS","description":"Below are the steps to create a controller in AngularJS:","step":[{"@type":"HowToStep","name":"Step 1) Create a basic HTML Page","text":"Before we start with the creation of a controller, we need to first have our basic HTML page setup in place.","image":"https://cdn.guru99.com/images/AngularJS/010416_0650_AngularJSCo3.png","url":"https://www.guru99.com/angularjs-controller.html#step1"},{"@type":"HowToStep","name":"Step 2) Check the files and file structure","text":"Secondly, let\u2019s look at our files and file structure which we are going to start with for the duration of our course.","image":"https://cdn.guru99.com/images/AngularJS/010416_0650_AngularJSCo4.png","url":"https://www.guru99.com/angularjs-controller.html#step2"},{"@type":"HowToStep","name":"Step 3) Use AngularJS code to display the output","text":"Use the given code to display the words \u201cAngularJS\u201d in both text format and in a text box when the page is viewed in the browser.","image":"https://cdn.guru99.com/images/AngularJS/010416_0650_AngularJSCo5.png","url":"https://www.guru99.com/angularjs-controller.html#step3"}]},{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Can the same controller be attached to more than one element?","acceptedAnswer":{"@type":"Answer","text":"Yes. AngularJS creates a separate instance and a separate scope for every element carrying the directive. The instances share no state, so a change in one does not appear in the other."}},{"@type":"Question","name":"When should a controller be declared in a route instead of ng-controller?","acceptedAnswer":{"@type":"Answer","text":"Declare it in the route when the controller belongs to a whole view loaded by routing. Use ng-controller for a component that appears inside a page regardless of the current route. Never declare both, or the controller runs twice."}},{"@type":"Question","name":"How do I stop dependency injection breaking after minification?","acceptedAnswer":{"@type":"Answer","text":"Use the array annotation, listing dependency names as strings before the function. Minifiers rename function arguments but never string literals, so the injector still resolves $scope and any services correctly."}},{"@type":"Question","name":"Can AI generate an AngularJS controller from a description?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI assistants produce the module, controller and scope bindings from a plain description of the screen. Always check the dependency annotation, since generated code often omits it."}},{"@type":"Question","name":"How does AI help migrate $scope controllers to controllerAs?","acceptedAnswer":{"@type":"Answer","text":"AI tools rewrite scope assignments as properties on a captured vm variable and prefix every matching view binding with the alias. Review $watch calls and event listeners by hand, because those still require the scope object."}}]}],"@id":"https://www.guru99.com/angularjs-controller.html#schema-61299","isPartOf":{"@id":"https://www.guru99.com/angularjs-controller.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/angularjs-controller.html#webpage"}}]}
```
