AngularJS Controller, Scope and View Tutorial Example

Filed Under: AngularJS

Earlier we looked at Angular Directives and its usage. Now we will shift our focus to the Model View Controller (MVC) part of AngularJS. We will discuss about the Controller, View and the Scope (view model) in this tutorial.

Contents

Controller, Scope and View Concepts

Controllers are JavaScript objects that controls the view data of angular applications. In the previous post, we looked at some of the Angular directives and the data binding concepts. We use controllers to control the data that are bound to the View and Scope acts as glue between the View and Controller.

MVC-angular

The directive ng-controller is used to attach the application controller to the DOM and angular will instantiate a new controller object and a new child scope will be available to the constructor of the controller. The new child scope can be injected into constructor as $scope.

Scope is an execution context for the angular expressions and it can watch expressions and propagate events. Scopes also provides APIs to watch the changes in the model and view. Scope ties the view to the controller so that it does not need to know the view and the view does not need to know about the controller.

Guidelines

AngularJS official documentation provides the following guidelines to use the controllers in the angular applications.

  • Use controllers to set up the initial state of the $scope object and add behavior to that object.
  • Do not use controllers to manipulate DOM. It should contain only business logic. Use Data Binding and Directives for DOM manipulation.
  • Do not use controllers to format inputs – Use Angular Form controls.
  • Do not use to filter output – Use Angular Filters.
  • Do not use controllers to share code or state across controllers – Use Angular Services.
  • Do not manage the life cycle of other components using controllers.

We will see features like Angular Form controls, Filters and Services in the upcoming tutorials.

Controller and Scope Examples

In this section, we will show how to define controllers in your angular applications.

Simple Usage of Controller and Scope

The following example demonstrates the Controller and Scope concept. Here, we will see how controllers sets the initial state of a $scope object.

angular-controller.html


<!DOCTYPE html>
<html>

<head>
<title> AngularJS - Controllers and Scope</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>

<body>

<div ng-app="" ng-controller="blogController">

	First Name: <input type="text" ng-model="firstName"><br>
	Last Name: <input type="text" ng-model="lastName"><br>
	<br>
	Full Name: {{firstName + " " + lastName}}
	<br>
	Blog Name : {{blogName }}

</div>

<script>
//Controller
function blogController($scope) {
    	$scope.firstName = "Pankaj",
    	$scope.lastName = "Kumar",
    	$scope.blogName = "JournalDev"
}

</script>

</body>
</html>

You will see the following output in your browser.

Application Details:

  • The ng-controller directive is used to attach the the Controller ( blogController, in the above example) to the DOM.
  • A new child scope will be available as a parameter to the to the Controller’s constructor function as $scope.
  • The Controller (blogController) set up the initial state of the $scope object. In our example, we set the initial state by attaching properties like firstName, lastName and blogName
  • We use ng-model directive to bind the input fields to the blogController properties.

Adding behavior to Controller

The following example demonstrates how to add behaviour to controllers. In Angular, we add behavior to the scope by attaching methods to the $scope object.

In the following example we attach the addEmployee() method to add a new behaviour to the controller. A new item will be pushed to the array of names when we click on the Add button.

controller-methods.html


<!DOCTYPE html>
<html ng-app>
<head>
<title>AngularJS - Controllers and Scope</title>
<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>

<div ng-controller="EmployeeController">

     Employee Name : <input type="text" ng-model="newEmployee"/>
    <button ng-click="addEmployee()">Add</button>
    <h2>Employees</h2>

    <ul>
        <li ng-repeat="name in names"> {{ name }} </li>
    </ul>

</div>
<script>

    function EmployeeController($scope) {
        $scope.names = [ "Elano Blumer","Iain Hume"];

        $scope.addEmployee = function() {
        	$scope.names.push($scope.newEmployee);
        	$scope.newEmployee = "";
        }
    }
</script>
</body>
</html>

Enter any name and click on add button. You will see the added names in the list below.

Application Details:

  • The ng-controller directive is used to attach the the Controller ( EmployeeController, in the above example) to the DOM.
  • A new child scope will be available as a parameter to the to the Controller’s constructor function as $scope.
  • The Controller (EmployeeController) set up the initial state of the $scope object. In our example, we set the initial state of the $scope with array of names.
  • We use ng-repeat directive to iterate over the employee names array.
  • We have attached addEmployee() method to add a behaviour to the above application. This line of code ($scope.names.push($scope.newEmployee);) will push new items in the input field to the names array when we click on the Add button.
  • The ng-click directive allows you to specify custom behavior when an element is clicked.

Using Controllers in External File

The following example demonstrates how to store and include controllers in external files

In the example, we have created a JavaScript file ( placeController.js ) to store the controller used in the application.

placeView.html


<!DOCTYPE html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
</script>
</head>
<body>
    <div data-ng-controller="PlaceController">
        Country:<input type="text" ng-model="countryName"/>
        City:<input type="text" ng-model="cityName"/>
        <button ng-click="addItem()">Add</button>
        <ul>
            <li ng-repeat="item in list">{{ item.country +"  : "+ item.city}}</li>
        </ul>
    </div>
    <script src="placeController.js"></script>
</body>
</html>

The controller used in the application, placeController.js

placeController.js


function PlaceController($scope) {
	$scope.list = [
		{ country: 'India',   city: 'New Delhi' },
		{ country: 'France',  city: 'Paris' },
		{ country: 'USA',     city: 'Washington DC' },
		{ country: 'England', city: 'London' }
	];

	$scope.addItem = function () {
		$scope.list.push({ country: $scope.countryName,
			    city: $scope.cityName });
	};
}

You will see the following output in your browser. Enter country name and city and then click on add button. You will see the added names in the list shown below.

Application Details:

  • The ng-controller directive is used to attach the the Controller ( PlaceController stored in placeontroller.js, in the above example) to the DOM.
  • A new child scope will be available as a parameter to the to the Controller’s constructor function as $scope.
  • The Controller (PlaceController) set up the initial state of the $scope object.
  • We use ng-repeat directive to iterate over the object list.
  • We have attached addItem() method to add a behaviour to the above application. This line of code ($scope.list.push({ country: $scope.countryName, city: $scope.cityName });) will push new items in the input field to the list of objects when we click on the Add button.
  • The ng-click directive allows you to specify custom behavior when an element is clicked.

In this tutorial, we demonstrated the use of controllers to set up the initial state of the $scope object and add behavior to that object.

That’s all for now and you will see more angular features in the coming posts.

Comments

  1. sushil says:

    Pretty good post to start up with Angular JS. How can i use with struts2 in java? i think you are expert in java. post would be appreciated.
    Please keep posting…

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages