pTutorial

New way to learn Programming

AngularJS Controller

The AngularJS Controller basically JavaScript constructor function that is used to pass the AngularJS Scope.

In other word controller is used to control the data in the whole application.

AngularJS Controller

This example explain the concept of the angular controller with point to point explanation.

<html>
<head>
<title>Angular JS Controller Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/
angularjs/1.3.14/angular.min.js"></script>
</head>

<body>
<h2>AngularJS Sample Controller Application</h2>

<div ng-app = "ukApp" ng-controller = "ukController">
Enter first name: 
<input type = "text" ng-model = "name.FName">
<br><br>
Enter last name: 
<input type = "text" ng-model = "name.LName"><br>
<br>         
Your Name: {{name.fullN()}}
</div>

<script>
var mainApp = angular.module("ukApp", []);
mainApp.controller('ukController', function($scope) {
$scope.name = {
FName: "Umar",
LName: "Farooque",

fullN: function() {
var studentObject;
studentObject = $scope.name;
return studentObject.FName + " " + studentObject.LName;
}
};
});
</script>

</body>
</html>


Explanation of controller example

The angular Application always starts from directive ng-app so ng-app=”ukApp” is the starts point and end where the div is end.

The ng-controller="ukController " attribute is an AngularJS directive that is used for defining the controller.

The ukController function is a JavaScript function with $scope, this is dependency injection that’s built into AngularJS.

AngularJS will invoke the controller with a $scope object.

$scope.name is property of studentController object.

FName and LName are two properties of $scope.name object. They have some default value.

fullN is the function of $scope.name object which return the full name including first name and last name.


Note: We can also defined the controller object in separate JavaScript and use that particular file in HTML.

See Also


QUOTES OF THE DAY

We live in this world when we love it.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER