What is a Controller in AngularJS?

In AngularJS, everything is associated with scope. Scopes are organized hierarchically. $rootScope object, the parent of all the scopes of the AngularJS application, and scopes are available created by directives. The scope hierarchy is consistent with the DOM tree hierarchy. A new scope is created whenever a scope-creating directive is encountered in the DOM tree.

Instead of defining model variables directly on the global $rootScope, like we d0 with the ng-init directive, we can group them inside a controller, which is simply a normal JavaScript function with a $scope argument.

A controller is defined in the HTML with a ng-controller directive specifying the name of the JavaScript variable which represents the controller. In below example, we have defined simpleController variable in a separate JavaScript file and that is our controller.

A controller creates a new scope, so We can define our model variables on the scope created by a controller. Also we can define functions on the $scope object.

The $scope argument in simpleController function is the scope associated to our new controller. The scope is created for us by AngularJS and made available to our controller function through Dependency Injection (DI). Dependency Injection simply means that we declare that our function depends on a $scope object (specifying it as a function argument) and AngularJS should make it available for us so we can use it inside the function.

In the example, the firstName and lastName variables and the getFullName function are defined in the $scope object managed by our simpleController. We don’t need to specify the $scope object in the HTML template because it’s implicit in the DOM tree rooted where the ng-controller directive is specified.

First name: {{firstName}}
Last name:
Full name: {{getFullName()}}


Close