In AngularJS Application, angularJS Controller controls the application data. In this article we will try to learn how to write our first AngularJS controller. Below are new terms
- Model – The data required for view
- View – Its the HTML
- Controller – A JavaScript function which controls the data of the view.
- $scope – Its the glue between Controller and view.
[example title=”$scope”]
This $scope object is a plain old JavaScript object. We can add and change properties on the $scope object however we see fit. This $scope object is the data model in Angular. Unlike traditional data models, which are the gatekeepers of data and are responsible for handling and manipulating the data, the $scope object is simply a connection between the view and the HTML. It’s the glue between the view and the controller.
All properties found on the $scope object are automatically accessible to the view.
[/example]
First Step to Write Controller:
[example title=”View”]
<div ng-app=”app” ng-controller=”someController”>
//Some more code
</div>
[/example]
[example title=”For the above view the Controller should be like this”]
<script>
var app = angular.module(‘app’, []);
app.controller(“someController”, function($scope) {
//Some logic here
});
</script>
[/example]
Explanation:
- angular is global object. Its ready to use in angularJS Application
- While creating controller ng-controller directive is used.
- AngularJS invokes the controller with a $scope object. AngularJS will take care of it to pass it.
- app.controller is a function where we passed two parameters. First one is controller name and second one is scope object.
[example title=”Complete Example”]
<!DOCTYPE html>
<html lang=”en-US”>
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js”></script>
<body>
<div ng-app=”app” ng-controller=”nameController”>
First Name:
<input type=”text” ng-model=”firstName”>
<br>
Last Name:
<input type=”text” ng-model=”lastName”>
<br>
<br>Full Name: {{firstName + ” ” + lastName}}
</div>
<script>
angular.module(“app”, []).controller(“nameController”, function($scope) {
$scope.firstName = “Hamidul”;
$scope.lastName = “Islam”;
});
</script>
</body>
</html>
[/example]
[tryit directory=”tryit” file=”write-your-first-angularjs-controller”]
Try It Yourself
[/tryit]