AngularJS controllers control the data of AngularJS applications.
AngularJS controllers are regular JavaScript Objects.
AngularJS Controllers
AngularJS applications are controlled by controllers.
The ng-controller directive defines the application controller.
A controller is a JavaScript Object, created by a standard JavaScript object constructor.
AngularJS Example
Application explained:
The AngularJS application is defined by ng-app="FirstApp". The application runs inside the <div>.
The ng-controller="FirstCtrl" attribute is an AngularJS directive. It defines a controller.
The FirstCtrl function is a JavaScript function.
AngularJS will invoke the controller with a $scope object.
In AngularJS, $scope is the application object (the owner of application variables and functions).
The controller creates two properties (variables) in the scope (FirstName and lastName).
The ng-model directives bind the input fields to the controller properties (FirstName and lastName).
Controller Methods
The example above demonstrated a controller object with two properties: LastName and firstName.
A controller can also have methods (variables as functions):
AngularJS Example
Controllers in External Files
In larger applications, it is common to store controllers in external files.
Just copy the code between the <script> tags into an external file named personController.js:
AngularJS Example
Another Example
For the next example we will create a new controller file:
Save the file as namesController.js:
And then use the controller file in an application:
AngularJS Example
Required fields are marked *
Get all latest content delivered to your email free.