AngularJS Controller Tutorial with Example

Abhigyan Singh 12th Jul 2020

This tutorial will explain about AngularJs Controller with live example. As we know that Controllers are the main directives who controls AngularJs application. Here we use ng-controller directive for controller example. Let us see live demo of AngularJs for better understanding.

What is Controller in AngularJS?

Controllers in AngularJS exist to augment the view of an AngularJS application. As we saw in our Two Way Data Binding example application, we did not use a controller, but only an implicit controller.

The controller in AngularJS is a function that adds additional functionality to the scope of the view. We use it to set up an initial state and to add custom behavior to the scope object.

When we create a new controller on a page, Angular passes it a new $scope. This new $scope is where we can set up the initial state of the scope on our controller. Since Angular takes care of handling the controller for us, we only need to write the constructor function.

Basically controller is a bridge to manage views and models, we can have multiple even nested i.e parent and child controllers in an app.

Setting up an initial controller looks like this:

SCRIPT:

var app = angular.module('myApp', []);
app.controller('expensesController', function($scope) {
$scope.message = "hi i am $scope's message from expensesController";
});
<div class="container">
<div><label>{{message}}</label></div>
</div>

Output will be given below:

hi i am $scope's message from expensesController

Firstly, we declared our app name in angular.module as myApp.

Then, under it we declared a controller using .controller named expensesController.

Then, we declared a variable in app's > controllers > scope as message and assigned it some value which we displayed in HTML output

Angular components we used in this example:

ng-app: ng-app directives is used to show the root element of angular js. All angular js application must have only have ng-app directive.

ng-controller: ng-controller directive is used to define angular js controller.

angular.module: A module is a collection of services, directives, controllers, filters, and configuration information.

$scope: $scope refers to application which is to use the studentController object.

app.controller: its used to declare a controller.

controller: AngularJS controllers control the data of AngularJS applications.

I have add app and under it controller in earlier expenses manager demo application on line number 36 in index.php file and line number 1,2 in app.js as mentioned below

Index.php

<?php

require_once("expenses.php");

$expenses = new expenses();

if(isset($_GET['action']) and $_GET['action'] == "getExpenses"){

echo $expenses-&gt;getExpenses();

exit;
}

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
echo $expenses->addExpenses($_POST);
exit;
}

if(isset($_GET['action']) and $_GET['action'] == "delete"){
$expenses->deleteExpense($_GET['id']);
exit;
}
?>

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header"><span class="navbar-brand"><img class="brand" src="img/logo.png" height="20" /> Expenses Tracker (Two Way Data Binding Demo)</span></div>
</div>
</nav>
<div class="container">
<div><!-- Add an Expenses --></div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="alert alert-warning">Please enter valid values in all required fields</div>
<div class="form-group"><input class="form-control" name="submitExpenseName" required="" type="text" placeholder="Expense Description" /></div>
<div class="form-group"><input class="form-control" name="submitExpenseAmount" required="" type="number" placeholder="Amount Spend" /></div>
<div class="form-group"><input class="form-control" name="submitExpenseDate" required="" type="date" /></div>
<div class="form-group"><button class="btn btn-success btn-lg btn-block" type="button"> Add</button></div>
</div>
</div>
<!-- List of Expenses -->
<div class="row">
<div class="col-xs-12">
<ul class="list-group">
<li class="list-group-item text-center"><span class="col-xs-8 pull-left text-left">{{expense.date}} {{expense.name}}</span>
Rs {{expense.amount}}
<button class="btn btn-danger pull-right btn-s" type="button"> </button></li>
</ul>
</div>
</div>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/angular.min.js"></script>
<script src="js/app.js"></script>

APP.JS

var app = angular.module('myApp', []);
app.controller('expensesController', function($scope, $http){
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$http.get("index.php?action=getExpenses")
.success(function(data){ $scope.expenses = data; });

$scope.addExpense = function(expense){
if("undefined" != expense.name){
$http({
method : "POST",
url : "index.php",
data : "action=add&amp;name="+expense.name+"&amp;amount="+expense.amount+"&amp;date="+expense.date
}).success(function(data){
$scope.expenses.unshift(data);
});
$scope.expense = "";
}
}

$scope.deleteExpense = function(index){
$http({
method : "GET",
url : "index.php?action=delete&amp;id="+$scope.expenses[index].id,
}).success(function(data){
$scope.expenses.splice(index,1);
});
}
});

You can see the live demo or download the copy of this tutorial. For any doubt and clarification, feel free to write in comment section.

Authored By Abhigyan Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

Also on DiscussDesk