Site icon ParallelCodes

AngularJS Controllers | ng-Controller

AngularJS Controllers

AngularJS Controllers attaches a controller class to the view. Controllers are used on HTML view using ng-Controller directive. Almost all the time you will use Controller to define a set of functionality and data-flow of your AngularJS app.

Controllers contains the business logic behind the application and defines the scope functions and values. The ng-Controller directive specifies a Controller class and attaches it to HTML view element.

Creating AngularJS controller:

<html>
<head>
<title>AngularJS - Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>

<script>
var app = angular.module("myApp",[]);
app.controller("myController",function($scope){
$scope.world = "Hello World";
});

</script>
</head>
<body ng-app='myApp'>
<div ng-controller='myController'>
{{world}}
</div>
</body>
</html>

VIEW DEMO

Here we are creating a controller with name myController. The body tag is using myApp and the div is using myController by using directive declaration : ng-controller='myController'{{world}} expression will print the message which is declared inside the controller using $scope.

OUTPUT:


Two different methods to create Controllers:

All controllers must belong to a module. You can create a variable for a AngularJS module and create controller for it with two differents ways. And use the controller by using ng-controller='ControllerName' on your HTML page.

Example:

<html>
<head>
<title>AngularJS - Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>
<script>
var app = angular.module("myApp",[]).controller("controller1", function($scope){
$scope.message = "I'm from Controller 1."
});

app.controller("controller2",function($scope){
$scope.message = "I was defined in Controller 2."
});

</script>
</head>
<body ng-app='myApp'>
<p ng-controller='controller1'> {{message}}</p>
<p ng-controller='controller2'> {{message}}</p>
</body>
</html>

VIEW DEMO

OUTPUT:


Controllers in a Separate file:

Most often times when creating AngularJS application, we will need to create a separate javascript file and define AngularJS app and its controllers.

Example:
<html>
<head>
<title>AngularJS - Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>
<script src="modules.js"></script>
</head>
<body ng-app='myApp'>
<p ng-controller='controller1'> {{message}}</p>
<p ng-controller='controller2'> {{message}}</p>
</body>
</html>

modules.js:

var app = angular.module("myApp",[]).controller("controller1", function($scope){
$scope.message = "I'm from Controller 1."
});

app.controller("controller2",function($scope){
$scope.message = "I was defined in Controller 2."
});

References: AngularJS API DOC


Exit mobile version