Angularjs add controller to module tutorial

AngularJS controller:

AngularJS controllers are used to control the data and flow of AngularJS applications. The ng-controller directive is used to define the AngularJS controller.

AngularJS module:

An AngularJS module defines an application and used to separate logics like services, controllers and application etc. It acts as a container for the different parts of an application.

Example Explanation:

First include the AngularJS library in the application. The ng-app directive initializes the application. We create a module named app and then add a controller appCtrl to it. Refer this controller with ng-controller directive in module.

Note: We can also add multiple controllers to a module. Click here to see multiple controllers example.

Output:

Example:

<!DOCTYPE html>
<html>
<script 
 src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<body>
 
<div ng-app="testApp" ng-controller="appCtrl">
{{ firstName + " " + lastName }}
</div>
 
<script>
var app = angular.module("testApp", []);
app.controller("appCtrl", function($scope) {
    $scope.firstName = "Vishal";
    $scope.lastName = "Gupta";
});
</script>
 
</body>
</html>

Try it:

JS Bin on jsbin.com

Please follow and like us:
Content Protection by DMCA.com