AngularJS Tutorial

Define AngularJS

Download AngularJS

AngularJS Expression

AngularJS vs Javascript

AngularJS Directives

AngularJS Module

AngularJS Controller

Custom Directive

AngularJS Scope

AngularJS Validation

AngularJS Filter

AngularJS SelectBox

AngularJS Directive

AngularJS Services

AngularJS Directives

AngularJS Routing

Interview Questions

AngularJS Controller

In Angular a controller is a JavaScript function which is used to control the data of AngularJS applications. The job of controller is to build a model for the view to display.

<div ng-app="myApp" ng-controller="myCtrl">
  Your Name is: {{ firstName + " " + lastName }}
</div>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
    $scope.firstName = "Mark";
    $scope.lastName = "Zuckerberg";
});
</script>

Note: When you make a controller in AngularJS, you have to pass the $scope object as an argument.

Modules and Controllers in Separate Files

It is common in AngularJS applications to put the module and the controllers in separate JavaScript files. In the example below, "myApp.js" contains an application module definition, while "myCtrl.js" contains the controller:

AngularJS.html File

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>

  <div ng-app="myApp" ng-controller="myCtrl">
    {{ firstName + " " + lastName }}
  </div>

  <script src="../AngularJS/myApp.js"></script>
  <script src="../AngularJS/myCtrl.js"></script>

</body>
</html>

myApp.js

var app = angular.module("myApp", []);

myCtrl.js

app.controller("myCtrl", function($scope) {
    $scope.firstName = "Mark";
    $scope.lastName= "Zuckerberg";
});

Angular Controller Method

In the above example, A controller object is used with two properties (variables) firstName and lastName. A controller can also have methods (functions)

<div ng-app="myApp" ng-controller="myCtrl">
Your Name is (without function): {{ firstName + " " + lastName }}
<br>
Your Name is (using function): {{ fun() }}
</div>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
    $scope.firstName = "Mark";
    $scope.lastName = "Zuckerberg";
	$scope.fun = function(){
		return $scope.firstName + $scope.lastName;
	}
});
</script>