Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is MVC
3.
Controller in Angular
3.1.
Script Tag
3.2.
External File
4.
Frequently Asked Questions
4.1.
What is a dynamic web application?
4.2.
What are examples of dynamic web applications?
4.3.
Is Angular open source?
4.4.
What are directives in AngularJS?
4.5.
How do I run an Angular JS app locally?
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

AngularJS Controllers

Introduction

AngularJs is a framework based on Javascript developed by Google to create web applications. AngularJs is an open-source framework that developers primarily use to build dynamic websites or web applications. The main reasons it is famous as a framework are its built-in services or modules and code reusability in the application.

introduction image

In this blog, we will discuss the AngularJS controllers. The AngularJS controllers are an essential part of Angular-based projects or, in general, one of the critical components of web architecture.

Before we talk about the AngularJS controller, we need to understand the Controller in terms of web architecture.

What is MVC

What is MVC

The MVC is a general web architecture on which most web applications are based. The full form of MVC is ‘Model View Controller’, and each of them is a separate component. The MVC helps us, the developer, to simplify the development process. MVC provides a general structure of the interaction and dependency between each component of MVC.


Let's discuss each of the components of the MVC.

Model

The role of the Model component is to manage the application's data. The model is a backend component that deals with the application's database.

View

The View component is responsible for the representation of the data which a user must see on the screen. The view is an interface for the user to interact with the application.

Controller

The controller works as a mediator between the Model and View Component. The role of the controller component is to deal with the user input and give the response accordingly.

For example, the user is updating the password on the website. So he needs to provide the previous password to authorize himself. The user first needs to type the password on the screen, which is the view, and a controller script then handles the request to validate the password, and then it will send to the Model component to verify the password with the database. The user will then get the response according to the validation done by the controller script of the application.

Now let's discuss the AngularJS controller and how we can implement it in an Angular project.

Controller in Angular

Now that we have understood the general idea of the controller. let's implement the controller component in an Angular project.

There can be multiple controllers in a complex web application. A modern web application consists of several modules, each with its functionality, view component, controller component, and many other things.

So it can be complex to keep track of each controller. But in AngularJS, we can create a module and a controller specific to that module. We can label unique names for each controller and module.

The controller in AngularJS controls the flow of the data and binds the data using the Javascript objects. We can implement the controller in AngularJS using the ng-controller directive. But before we define the controller, we need to define the module that that particular controller will control.

The ng-controller directive adds behavior or maintains data in an HTML element and its child elements by specifying a controller.

Syntax:

<element ng-controller="expression">Contents...</element>


To define a module, we use the ng-app directive in AngularJS.

Example

<!DOCTYPE html>
<html>
    <head>
        <script src="https: //ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
    </head>
    <body>
        <div ng-app="ninjaApp"></div>
    </body>
</html>


As you can see in the <div> tag, we have defined our module and named it ninjaApp. You can define the ng-app in any tag according to your requirement.

After that, we need to define our controller to control the data of the module we have created. We will some functionality to print the message on the screen.

<!DOCTYPE html>
<html>
    <head>
        <script src="https: //ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
    </head>
    <body ng-app="ninjaApp">
        <div ng-controller="ninjaController">        {{message}}    </div>
        <script>
            var myApp = angular.module('ninjaApp', []);
            myApp.controller('ninjaController', function($scope) {
                $scope.message = "Hello Ninjas!";
            });
        </script>
    </body>
</html>


Let's understand the above code:

example explanation

Output

example output

Our next step will define the functionality of this controller. There are two ways to implement the controller functionality.

  1. To implement this using <script> tag.
  2. To implement this using an external file.

Script Tag

First, we will implement the <script> tag method.

Let's create an Angular project to display the user's thoughts on the screen. We have already defined our module and controller. Let's just add the functionality.

In the script tag, we will create a module and store it in a variable called Appmodule. In the parameter of the ‘.module’ method, you must write the module name defined in the HTML file.

<script>
     var Appmodule = angular.module("TestingModule", []);
</script>


Next, we will create the controller script.

<script>
     var Appmodule = angular.module("TestingModule", []);
     Appmodule.controller("Module1-ctrl", function($scope) {})
</script>


With the Appmodule variable, we can access the .controller method, and in the method, we need to write the controller's name and function as a second parameter.

In the function($scope), we will define the functionality of our controller. The $sccope is a Javascript object which we will use to define and create variables or functions so we can use these variables or functions in the HTML where we have defined the controller.

<script>
     var Appmodule = angular.module("TestingModule", []);
     Appmodule.controller("Module1-ctrl", function($scope) {
         $scope.thought = "There is way and there is a will!!"
     })
</script>


Here we have defined $scope.thought, and we will display this thought on the HTML file. To access the $scope variable in HTML we need to use the {{variable name}}.

We will also use the ng-model directive to bind the thought variable with user input. 

<div ng-app="TestingModule" ng-controller="Module1-ctrl">
     <h1 style="font-family:'Lucida Sans';">THOUGHT OF THE DAY</h1>
     <h3>{{thought}}</h3>       
     Write your thought: <input type="text" ng-mode="thought>
</div>


The <input> tags have ng-model and are binded with the thought variable in the controller.

Code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <script src="https: //ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
        <script>
            var Appmodule = angular.module("TestingModule", []);
            Appmodule.controller("Module1-ctrl", function($scope) {
                $scope.thought = "In order to be irreplaceable, one must always be different"
            })
        </script>
    </head>
    <body>
        <div ng-app="TestingModule" ng-controller="Module1-ctrl">
            <h1 style="font-family:'Lucida Sans';">THOUGHT OF THE DAY</h1>
            <h3>”{{thought}}”</h3>       Write your thought: <input type="text" ng-model="thought">
        </div>
    </body>
</html>


Output

code output

After changing the thought:

code output after changing the thought

When we change the value in the input field, it will be reflected on the screen. The reason is that we have binded the $scope.thought object with the input field using the ng-model directive.

External File

We can create the same code using an external Javascript file. If you need to implement multiple modules and controllers, then using a separate Javascript file is best.

example.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <script src="https: //ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
        <script src="example.js"></script>
    </head>
    <body>
        <div ng-app="TestingModule" ng-controller="Module1-ctrl">
            <h1 style="font-family:'Lucida Sans';">THOUGHT OF THE DAY</h1>
            <h3>"{{thought}}"</h3>       Write your thought: <input type="text" ng-model="thought">
        </div>
    </body>
</html>
</html>


example.js

var Appmodule = angular.module("TestingModule", []);
Appmodule.controller("Module1-ctrl", function($scope) {
	$scope.thought = "In order to be irreplaceable, one must always be different"
})
You can also try this code with Online Javascript Compiler
Run Code


Output

external file code output

Frequently Asked Questions

What is a dynamic web application?

The dynamic web application is an application that works in real time. The content in the dynamic web application must be updated regularly.

What are examples of dynamic web applications?

E-commerce websites, blog applications, etc, are two examples of dynamic web applications.

Is Angular open source?

Yes, Angular is an open-source web framework developed by Google.

What are directives in AngularJS?

Directives are labels that we can use to extend our basic HTML structure and add some functionality to it, for example, data binding.

How do I run an Angular JS app locally?

An Angular application can be compiled and run locally using the command ng-serve. This opens the localhost on your system.

Conclusion

In this blog, we have discussed the AngularJS controller. We have learned about the controller in general and MVC architecture. Then we discussed and implemented the AngularJS controller with an example.

To learn more about AngularJS, you can check out the following articles.

To learn more about DSA, competitive coding, and many more knowledgeable topics, please look into the guided paths on Coding Ninjas Studio. Also, you can enroll in our courses and check out the mock test and problems available to you. Please check out our interview experiences and interview bundle for placement preparations.

Happy Coding!

Live masterclass