Controller
Description
AngularJS controller adds functionality to the $scope of the view.
When we create a controller, AngularJS passes it a new $scope
.
We can use controller to set up an initial value and add custom behavior to the $scope object.
Declaring the ng-controller
attribute on an element
makes all of the elements inside of the element belong to the controller.
The controller function takes one parameter, the $scope
of the element.
$scope
object, available on the element and the controller,
is the bridge between the controller and the view.
Example
The following code shows how to create a controller.
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
</head><!-- w w w . j a v a2s.c om-->
<body>
<div ng-controller="MyController">
<h1>{{ person }}</h1>
and their name:
<h2>{{ person.name }}</h2>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
$scope.person = {
name: "Angular JS"
};
});
</script>
</body>
</html>
Example 2
The following example creates an object and wraps the data as its properties.
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js">
</script><!-- w ww.ja v a 2 s. co m-->
</head>
<body>
<div ng-controller="SimpleController">
<h1>Hello {{ myDateTime.now }}!</h1>
</div>
<script type="text/javascript">
function SimpleController($scope) {
$scope.myDateTime = {
now: new Date()
};
var updateMyDateTime = function() {
$scope.myDateTime.now = new Date()
};
setInterval(function() {
$scope.$apply(updateMyDateTime);
}, 1000);
updateMyDateTime();
};
</script>
</body>
</html>