Site icon Pro Liferay

Write Your First AngularJS Controller

Write-Your First-AngularJS- Controller


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 


[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:

[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]

Exit mobile version