<!DOCTYPE html> <html> <head> <script src="angular.js"></script> <script src="script.js"></script> </head> <body ng-app> <div ng-controller="simpleController"> <strong>First name:</strong> {{firstName}}<br /> <strong>Last name:</strong> <span ng-bind="lastName"></span><br /> <strong>Full name:</strong> {{getFullName()}}<br /> <br /> <label>Set the first name: <input type="text" ng-model="firstName"/></label><br /> <label>Set the last name: <input type="text" ng-model="lastName"/></label> </div> </body> </html>
var simpleController = function ($scope) { // Initialize the model variables $scope.firstName = "John"; $scope.lastName = "Doe"; // Define utility functions $scope.getFullName = function () { return $scope.firstName + " " + $scope.lastName; }; };



In AngularJS, everything has an associated scope. Scopes are organized in a hierarchy. There is a $rootScope object, the parent of all the scopes of the AngularJS application, and there are scopes created by some directives. The scope hierarchy is coherent with the DOM tree hierarchy. Whenever a scope-creating directive is encountered in the DOM tree, a new scope is created.

Instead of defining model variables directly on the global $rootScope, like we did with the ng-init directive, we could 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 representing the controller. In the example, we've defined the simpleController variable in a separate JavaScript file and that's our controller.

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

The $scope argument in the 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.