Updated March 23, 2023
Introduction to Controllers in AngularJS
At the core, Controller is nothing but a Javascript function in an AngularJS application. AngularJS framework attaches some special behaviors to the Controller function. The special about these controller functions is that controllers receive $scope (a Javascript object) as an argument. The controller is one of the basic building blocks of MVC architecture provided by the AngularJS framework, and it contains business logic and keeps view and model in sync.
$scope is a glue between view and controller. The controller has data and it passes that data and to view with the help of $scope. The view is the DOM layer and a controller is a connecting wire between this DOMlayer and business data. A controller can be associated with DOM in the following ways:
- By using ngController.
- By defining the route and an associated.
- Controller to a regular.
The controller is mainly used for setting up an initial $scope object and adding behavior to $scope. Ideally Controller should be slim and do just minimal business logic needed for the attached view, the general design approach to keep controller slim is to pass common and repetitive logic to angular services or factories and inject these services to all the controller where ever needed. Application relay on controllers for the flow of data and sync of view with model.
Implementing Controllers in AngularJS Application
The ng-controller directive is the most common way to attach a controller to a view. Angular provides controller function to add a controller to the angular module, here the first parameter is the name of the controller and second is an array of dependencies and controller function.
This is an example that creates MyController, and attaches a name property containing the string ‘John’ to the $scope:
Code:
var firstApp = angular.module('firstApp',[]);
firstApp.controller('MyController', ['$scope', function($scope) {
$scope.name = 'John';
}]);
This code snippet creates an angularJS module name first app and attaches a controller to the module named MyController. As described above, MyController receives $scope object and adds property name to it, with value “John”.
As next step, we have to associate this controller to a view or HTML snippet, here is the code example to attached MyController to a view or DOM.
Code:
<div ng-controller="MyController">
Hello, I am {{name}}
</div>
This HTML code snippet attaches “MyController” created in above example to a view using ng- controller directive, it also renders name property of $scope object on view/template.
We can also attach methods or functions to Controller and call them from view or DOM layer upon specific event.
Code:
var myApp = angular.module('myApp', []);
myApp.controller('ClickController', ['$scope', function($scope) {
$scope.count = 0;
$scope.clicked = function() {
$scope.count++;
};}]);
This code snippet shows how a method can be attached to DOM with the help of a controller, in this example, ClickController has a method clicked, which add one to count property of the $scope object.
This below code of HTML continues the above example.
Code:
<div ng-controller="ClickController">
<button ng-click="clicked()">Click Here</button>
<p>You have clicked {{count}} times!</p>
</div>
In this view template, ClickController is attached to div using ng-controller directive, on click of the button in view the count property of the scope object increments by one and view is updated accordingly.
Nested Controllers
As we have nested functions, so in the same way we can also create a nested controller in AngularJS Applications. In the scenarios of nested controllers child controller can always access the properties and methods of parent or enclosing controller but the parent controller will not have access to properties and methods of child controller.
Code:
<body ng-app="myApp">
<div ng-controller="parentController">
Message: {{parentsMessage}}
<div ng-controller="childController">
Parent Message: {{ parentsMessage}} </br>
Child Message: {{ChildsMessage}}
</div>
Child Message: {{ ChildsMessage}}
</div>
</body>
This is a code example showing nested controllers, parentController is the parent of child controller, both are in the same angular module and have their own data and methods. The child controller will be able to access messages from parentController and can render it on DOM. Place parent Controller, will not be able to access child controller’s property i.e. ChildMessage.
Code:
var ngApp = angular.module('myApp', []);
ngApp.controller('parentController', function ($scope) {
$scope. parentsMessage = "Hello from Parent Controller";
});
ngApp.controller('childController', function ($scope) {
$scope. ChildsMessage = " Hello from Child Controller ";
});
This is the Javascript code for the ngApp module and the controllers defined in the module.
i.e. parentController and childController.
Methods in AngularJs Controller
As mentioned earlier we can have methods in Controller and they can be also passed in view or DOM, here is a code example to demonstrate the methods in the controller and use of the method in the view template.
Code:
<div ng-app="myApp" ng-controller="employeeCtrl"> First Name: <input type="text" ng-model="fName"><br> Last Name: <input type="text" ng-model="lName"><br>
<br>
Full Name: {{getFullName()}}
</div>
In this example we have two properties “fName” and “lName” and a method name getFullName in $scope object passed to employee controller. In this template/view, we are calling/invoking the getFullName method in template or view. In this template ng-model, angularJS directive is used to achieve two-way data binding or to pass updates from view to model.
Code:
var myApp = angular.module('myApp', []); myApp.controller(‘employeeCtrl’, function($scope) {
$scope.fName = "John";
$scope.lName = "Dee";
$scope. getFullName = function() {
return $scope. fName + " " + $scope. lName;
}; });
This is a controller function used in the above view and is using data and method exposed by the employeeCtrl to the view/DOM. This code shows how we can define the controller and the above snippet shows how to use it in the view.
Controller with Dependencies
Most of the time in real-world applications the controller will have additional dependencies, here is the code snippet that demonstrates how we can create a Controller and inject additional dependencies into it.
Code:
Var myApp = angular.module('myApp',['ui.client, 'ngEmp']); App.controller('myController', ['$log', '$location', function($log, $location, $scope)
{
$scope.name =”John”;
$scope.sayHello = function(){alert('say hello');}
$log.log('I am using log service');
$location.path("/myPath")
}]);
In this example myController is having additional dependencies those are location and log service, these dependencies are added into an array and then in Controller function and in the end, these services are used in the controller for logging and navigation.
Recommended Articles
This is a guide to Controllers in AngularJS. Here we discuss the Introduction and AngularJs Controller Methods with Examples along with Creation and Use of Controllers in AngularJS Application. You may also have a look at the following articles to learn more –