Controllers will have your core business logic. The primary purpose of controller in Angular.js is to take the data from the View, process the data accordingly and then send that data across to the view which is displayed to the end user.

It will use the data model, carry out the required processing and then pass the output to the view which in turn is displayed to the end user.




In this tutorial, you will learn-

What controller does from Angular' s perspective

AngularJS Controller: Learn in 10 Minutes!

  • 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.
  • The properties of the view can call "functions" on the scope. And events on the view can call "methods" on the scope. The below code snippet gives a simple example of a function.
    • The function($scope) which is defined when defining the controller and an internal function which is used to return the concatenation of the $scope.firstName and $scope.lastName.
    • In AngularJS when you define a function as a variable, it is known as a Method.

AngularJS Controller: Learn in 10 Minutes!

  • Data in this way passes from the controller to the scope and then the data passes back and forth from the scope to the view.
  • The scope is used to expose the model to the view. The model can be modified via methods defined in the scope which could be triggered via events from the view. We can define two way model binding from the scope to the model.
  • Controllers should not ideally be used for manipulating the DOM. This should be done by the directives which we will see later on.
  • Best practice is to have controller's based on functionality. For example, if you have a form for input and you need a controller for that, create a controller called "form controller".

Building a basic controller

Before we start with the creation of a controller, we need to first have our basic html page setup in place.

The below code snippet is a simple html page which has a title of "Event Registration" and has references to important libraries such as bootstrap, jquery and Angular.

AngularJS Controller: Learn in 10 Minutes!

  1. We are adding references to the bootstrap CSS stylesheets, which will be used in conjunction with the bootstrap libraries.
  2. We are adding references to the angularjs libraries. So now whatever we do with angular.js going forward will be referenced from this library.
  3. We are adding references to the bootstrap library to make our web page more responsive for certain controls.
  4. We have added references to jquery libraries which will be used for DOM manipulation. This is required by Angular because some of the functionality in Angular is dependent on this library.

By default the above code snippet will be present in all of our examples, so that we can show just the specific angularJS code in the subsequent sections.

Secondly let's look at our files and file structure which we are going to start with for the duration of our course.

AngularJS Controller: Learn in 10 Minutes!

  1. First we segregate our files into 2 folders as is done with any conventional web application. We have the "CSS" folder. It will contain all our cascading style sheet files, and then we will have our "lib" folder which will have all our JavaScript files.
  2. The bootstrap.css file is placed in the CSS folder and it used for adding a good look and feel for our website.
  3. The angular.js is our main file which was downloaded from the angularJS site and kept in our lib folder.
  4. The app.js file will contain our code for the controllers.
  5. The bootstrap.js file is used to supplement the bootstrap.cs file to add bootstrap functionality to our web application.
  6. The jquery file will be used to add DOM manipulation functionality to our site.

Let see an example on how to use angular.js,

What we want to do here is just to display the words "AngularJS" in both text format and in a text box when the page is viewed in the browser.

AngularJS Controller: Learn in 10 Minutes!

Code Explanation:

  1. The ng-app keyword is used to denote that this application should be considered as an angular application. Anything that starts with the prefix 'ng' is known as a directive. "DemoApp" is the name given to our Angular.JS application.
  2. We have created a div tag and in this tag we have added an ng-controller directive along with the name of our Controller "DemoController". This basically makes our div tag the ability to access the contents of the Demo Controller. You need to mention the name of the controller under the directive to ensure that you are able to access the functionality defined within the controller.
  3. We are creating a model binding using the ng-model directive. What this does is that it binds the text box for Tutorial Name to be bound to the member variable "tutorialName".
  4. We are creating a member variable called "tutorialName" which will be used to display the information which the user types in the text box for Tutorial Name.
  5. We are creating a module which will attached to our DemoApp application. So this module now becomes part of our application.
  6. In the module, we define a function which assigns a default value of "AngularJS" to our tutorialName variable.

If the command is executed successfully, the following Output will be shown when you run your code in the browser.

Output:

AngularJS Controller: Learn in 10 Minutes!

Since we assigned the variable tutorialName a value of "Angular JS", this gets displayed in the text box and in the plain text line.

Controller Methods

Normally, one would want to define multiple methods in the controller to separate the business logic.

For example, suppose if you wanted to have your controller do 2 basic things, one is to perform the addition of 2 numbers and the other is to perform the subtraction. You would then ideally create 2 methods inside of your controller, one to perform the addition and the other to perform the subtraction.

One can define custom methods within an Angular.JS controller.

The example below shows how this can be done.

AngularJS Controller: Learn in 10 Minutes!

Code Explanation:

  1. Here, we are just defining a function which returns a string of "AngularJS". The function is attached to the scope object via a member variable called tutorialName.

If the command is executed successfully, the following Output will be shown when you run your code in the browser.

Output:

AngularJS Controller: Learn in 10 Minutes!

Controllers in External Files

Let's look at an example of "HelloWorld" where all of the functionality was placed in a single file. Now it's time to place the code for the controller in separate files.

Let's follow the steps below to do this.

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

AngularJS Controller: Learn in 10 Minutes!

The above code does the following things,

  1. Define a module called "app" which will hold the controller along with the controller functionality.
  2. Create a controller with the name "HelloWorldCtrl". This controller will be used to have a functionality to display a "Hello World" message.
  3. The scope object is used to pass information from the controller to the view. So in our case, the scope object will be used to hold a variable called "message".
  4. We are defining the variable message and assigning the value "Hello World" to it.

Step 2) Now, in your Sample.html file add a div class which will contain the ng-controller directive and then add a reference to the member variable "message"

Also don't forget to add a reference to the script file app.js which has the source code for your controller.

AngularJS Controller: Learn in 10 Minutes!

If the above code is entered correctly, the following Output will be shown when you run your code in the browser.

Output:

AngularJS Controller: Learn in 10 Minutes!

Managing Scope

The scope is a JavaScript object which basically binds the "controller" and the "view". One can define member variables in the scope within the controller which can then be accessed by the view.

AngularJS Controller: Learn in 10 Minutes!

Code Explanation:

From the above code snippet you can see that we can define multiple member variables like tutorial name, name, topic, etc. and assign them the relevant values.

In our div tag, we can the display these values accordingly. Hence as we mentioned before the scope object is the main object which is used to pass information from the controller to the view.

Setting up or adding Behavior

In order to react to events or execute some sort of computation/processing in the View, we must provide behavior to the scope.

Behaviors are added to scope objects to respond to specific events that may be triggered by the View. Once the behavior is defined in the controller, it can be accessed by the view.

Let's look at an example of how we can achieve this.

AngularJS Controller: Learn in 10 Minutes!

Code Explanation:

  1. We are creating a behavior called "fullName". This behavior is a function which accepts 2 parameters (firstName,lastname).
  2. The behavior then returns the concatenation of these 2 parameters.
  3. In the view we are calling the behavior and passing in 2 values of "Guru" and "99" which gets passed as parameters to the behavior.

If the command is executed successfully, the following Output will be shown when you run your code in the browser.

Output:

AngularJS Controller: Learn in 10 Minutes!

In the browser you will see a concatenation of both the values of Guru & 99 which were passed to the behavior in the controller.

Displaying repeated information

Sometimes we may be required to display a list of items in the view , so the question is that how can we display a list of items defined in our controller onto our view page.

Angular provides a directive called "ng-repeat" which can be used to display repeating values defined in our controller.

Let's look at an example of how we can achieve this.

AngularJS Controller: Learn in 10 Minutes!

Code Explanation:

  1. In the controller we first define our array of list items which we want to define in the view. Over here we have defined an array called "TopicNames" which contains 3 items. Each item consists of a name-value pair.
  2. The array of TopicsNames is then added to a member variable called "topics" and attached to our scope object.
  3. We are using the html tags of <ul>(Unordered List) and <li>(List Item) to display the list of items in our array. We then use the ng-repeat directive for going through each and every item in our array. The word "tpname" is a variable which is used to point to each item in the array topics.TopicNames.
  4. In this, we will display the value of each array item.

If the code is executed successfully, the following Output will be shown when you run your code in the browser. You will see all items of the array (Basically the TopicNames in topics) displayed.

Output:

AngularJS Controller: Learn in 10 Minutes!

A more advanced controller

An advanced controller example would be the concept of having multiple controllers in an angular JS application.

You might want to define multiple controllers to separate different business logic functions. Earlier we mentioned about having different methods in a controller in which one method had separate functionality for addition and subtraction of numbers. Well you can have multiple controllers to have a more advanced separation of logic. For example you can have one controller which does just operations on numbers and the other which does operations on strings.

Let's look at an example of how we can define multiple controllers in an angular.JS application.

AngularJS Controller: Learn in 10 Minutes!

Code Explanation:

  1. Here we are defining 2 controllers called "firstController" and "secondController". For each controller we are also adding some code for processing. In our firstController , we attach a variable called "pname" which has the value "firstController", and in the secondController we attach a variable called "lname" which has the value "secondController".
  2. In the view, we are accessing both controllers and using the member variable from the second controller.

If the code is executed successfully, the following Output will be shown when you run your code in the browser. You will see all text of "secondController" as expected.

Output:

AngularJS Controller: Learn in 10 Minutes!

Summary

  • The controller's primary responsibility is to create a scope object which in turn gets passed to the view
  • How to build a simple controller using the ng-app, ng-controller and ng-model directives
  • How to add custom methods to a controller which can be used to separate various functionalities within an angularjs module.
  • Controllers can be defined in external files to separate this layer from the View layer. This is normally a best practice when creating web applications.
  • Various member variables can be added to the scope object which can then be referenced in the view.
  • Behavior can be added to work with events which are generated for actions performed by the user.
  • The ng-repeater directive can be used to display multiple repeating items.
  • We also had a look at an advanced controller which looked at the definition of multiple controllers in an application.

 

YOU MIGHT LIKE: