AngularJS - Controllers

What is Controller ?

The controller in AngularJS is a JavaScript function that maintains the application data.Controller job is to build a model for the view to display. Model is nothing but data of the application. In a real world application the control may called a webservices which will retrieve data from the database.


A controller is nothing but a constructor function which is instantiated by AngularJS when it encounters ng-controller directive in HTML.


Why we need controllers ?

The role of controllers in Angular is to expose data to our view via $scope, and to add functions to $scope that contain business logic to enhance view behaviour.

Don’t worry if you got confused with above points. Shortly this all will make sense once we create a small example using controller.

What is Controller ?

The controller in AngularJS is a JavaScript function that maintains the application data.Controller job is to build a model for the view to display. Model is nothing but data of the application. In a real world application the control may called a webservices which will retrieve data from the database.


A controller is nothing but a constructor function which is instantiated by AngularJS when it encounters ng-controller directive in HTML.


Why we need controllers ?

The role of controllers in Angular is to expose data to our view via $scope, and to add functions to $scope that contain business logic to enhance view behaviour.

Don’t worry if you got confused with above points. Shortly this all will make sense once we create a small example using controller.

How to create a controller in AngularJS

Creating controller in AngularJS is very simple, just create a JavaScript constructor function. Setting up an initial controller looks like this:

var myController = function firstController($scope) {
 $scope.message = "hello world";
}

In the above code we are creating a function and assigning it to a variable myController. In the function we are passing a parameter $scope. $scope is an AngulaJS object which is passed automatically by AngulaJS framework. We need to attach the model with this scope object which will then available to the view. In the View we need to use data binding expression to retrieve the model values which need to be displayed on view.

In this example we are attaching the message property to scope object and within this property we are attaching the string hello world. So this message property will be available on view.


Now create a separate script file to create the controller.Steps to create the module is given below.

1. Create a module

var myApp = angular.module("myModule", []);

The first parameter of the module() method is name of module, here module name is "myModule". In the second parameter we are passing empty array because this module is not dependent on another module.

2. Create a controller

var myController = function($scope) {
$scope.message ="Hello World";
};

A controller is nothing but a javaScript function. We created an anonymous function and assigned to a variable "myController".In this scope object we attached a property "message" and initialized that with string "Hello World". So now our controller is ready.

Now the next step is to register this controller with the above module.

3. Register controller with the module

myApp.controller("myController", myController);

In the above code we called controller() function on module object "myApp".controller() function has two parameters, the first parameter is name of the controller. We provided name of the controller as "myController".The second parameter is the name of the controller. As name of the controller is "myController" so we passed myController as second parameter. We have registered a controller with the module.


Now consider the code to create a controller.

var myController = function($scope) {
$scope.message ="Hello World";
};

In the above code we have an anonymous function which we are assigning to a variable and then we are passing that variable in the controller() function to register the controller with the module.Instead of that we can specify the function inline in the second parameter of the controller() method. In this way we can eliminate the need of creating separate variable for controller.

Now the full and improved code for controller is given below.


var myApp = angular.module("myModule" , []);
myApp.controller("myController" , function($scope)) {
$scope.message ="Hello World";
});

Now we have a module and controller and that controller is registered with the module in the js file. We have to associate the module("myApp") with ng-app directive and controller("myController") with ng-controller directive in the view.

Now combine the definition of a module and controller in html and create a simple application page. The following example demonstrates attaching properties to the $scope object inside a controller and then displaying property value in HTML.

config.js

var myApp = angular.module("myModule" , []);
myApp.controller("myController" , function($scope)) {
$scope.message ="Hello World";
});

index.html

<!DOCTYPE html>
<html ng-app="myModule">
<head>
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="js/config.js"></script>
</head>
<body>
<div ng-controller="myController">
{{message}}
</div>
<div>
{{message}}
</div>
</body>
</html>

In the above example, ng-controller="myController" directive is applied to the div element where "myController" is the name of the controller. Inside div element, we have specified {{message}} expression. In the output only first div message will be displayed in the browser because controller is limited to first div only. Second div {{message}} property from the context object will not be available and hence it will not displayed in the browser.

Output

Hello World! 

Now move ng-controller directive to the body section of the html document and observe the output.

<!DOCTYPE html>
<html ng-app="myModule">
<head>
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="js/config.js"></script>
</head>
<body ng-controller="myController">
<div>
{{message}}
</div>
<div>
{{message}}
</div>
</body>
</html>

Now controller is available in entire body section and "message" property is available in entire children of the body section.

Output :

Hello World!
Hello World! 

Let us create another example of controller.

Example :

In below code snippet, we will see how to combine the definition of a module and controller and create a simple application page.

1. Create a js file to define module and controller

Create a JavaScript file config.js inside js folder and add below lines of code into this file.

config.js

var myApp = angular.module('myApp', []);
	myApp.controller('myController', function($scope) {
	        $scope.firstName = 'Mukesh';
		    $scope.lastName = 'Kumar';

	        $scope.showDetails = function () {            
        	    return $scope.firstName + ' ' + $scope.lastName;
	        };
	});

In the above js file We have created a Module for the page application where the application name is "myApp". After that we created a controller named "myController" and attached a function that has $scope injectable object. Next, we added two properties in $scope object (firstName and lastName). After that we have created a function named "showDetails" that returns a string with the value of firstName and lastName.



2. Create html file

index.html

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="js/config.js"></script>
</head>
<body>
<div ng-controller="myController">
		Your Full name is {{ showDetails() }}
	</div>
</body>
</html>

In the html file we are calling "showDetails()" method of controller.


Output

Your full name is Mukesh Kumar 


Summary of the Steps to create Controller

1) Create a javaScript function app.js where we will define controller.

2) Let's create module named myModule in app.js

angular.module('myModule', []);

The first parameter of the module() method is name of module, here module name is "myModule". In the second parameter we are passing empty array because this module is not dependent on another module.

3) Create our controller with the following code in app.js

angular.module('myModule').controller('MainCtrl', function (){
});

4) Inject $scope to our controller by specifying it as a parameter.

angular.module('myModule').controller('MainCtrl', function ($scope){
});

5) Set $scope.message with an object:

angular.module('myModule').controller('MainCtrl', function ($scope){
$scope.message = 'hello world';
});

6) Now our controller is ready to use, let's create a div with a paragraph that contains message from controller.

<div ng-app="myModule">
<h1>Controller Example</h1>
<div ng-controller="MainCtrl">
<p>
{{ message }}
</p>
</div>
</div>

AngularJS Controller without using any specific module name

Consider the piece of code given below.

html file

<body ng-app>
  <div ng-controller="sampleController">
    <strong>First name:</strong> {{firstName}}<br />
    <strong>Last name:</strong> <span ng-bind="lastName"></span><br />
    <strong>Full name:</strong> {{getFullName()}}<br />
    <br>
    <label>Set the first name: <input type="text" ng-model="firstName"/></label><br />

js file

var sampleController = function ($scope)
{
  // Initialize the model variables
  $scope.firstName = "Mukesh";
  $scope.lastName = "Kumar";

  // Define utility functions
  $scope.getFullName = function ()
  {
    return $scope.firstName + " " + $scope.lastName;
  };
};

In the above example we defined controller named "sampleController" without any module and its perfectly valid. Normally we will put our controllers in some module, whose name we need to define in ng-app of html document. How it works when I don't define any module ?

Angular, has this "auto-discover" feature, that allows it to look up controllers by their name if they are defined on the global scope. This feature is mainly intended for quick demos/prototypes/proof-of-concept snippets and not real-world applications.

Note:-Although Angular allows you to create Controller functions in the global scope, this is not recommended. In a real application you should use the .controller method of your Angular Module for your application [...].


AngularJS Controllers without any Scope

If an application does not depend upon communication with other controllers, or does not require any inheritance feature, you can use Scopeless Controllers. In the example given below, the data and behaviour of the controller is defined using JavaScript, no dependency on $scope.Controllers without scopes are useful for small applications, to avoid complexities.







References :- AngulaJS Documentation



Related Articles

  1. Maven Overview




comments powered by Disqus