Sunday, 17 May 2015

Controllers

Hi. Today, I am going to discuss about Controllers in Angular JS.

Let me explain you with an example.

Controller.html:-
<html>
<head>
<title>Angular JS Controller</title>
<script src="angular.min.js"></script>
</head>
<body>
<h2>Application On Angular JS Controller</h2>
<div ng-app="mainApp" ng-controller="studentController">
Enter first name: <input type="text" ng-model="student.firstName"><br><br>
Enter last name: <input type="text" ng-model="student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
</div>
<script src="Controller.js"> </script>
</body>
</html>

Controller.js:-
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Anik",
lastName: "Acharjee",
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});


Screenshot:-



Explanation:-

Here, $scope refers to application which is to use the studentController object. $scope.student is property of studentController object.

firstName and lastName are two properties of $scope.student object and passed the default values to them. fullName is the function of $scope.student object whose task is to return the combined name.

In fullName function we're getting the student object and then return the combined
name. ng-model is used to indicate studentController's student property.

Whatever we type in first name and last name input boxes, you can see the full name getting updated automatically.

No comments:

Post a Comment