Javatpoint Logo

91-9990449935

 0120-4256464

AngularJS Controllers

AngularJS controllers are used to control the flow of data of AngularJS application. A controller is defined using ng-controller directive. A controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control.


AngularJS Controller Example

Test it Now

Note:

  • Here, the AngularJS application runs inside the <div> is defined by ng-app="myApp".
  • The AngularJS directive is ng-controller="myCtrl" attribute.
  • The myCtrl 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).

AngularJS controller example with methods (variables as functions)

Test it Now

AngularJS Controller in external files

In larger applications, generally the controllers are stored in external files.

Create an external file named "personController.js" to store controller.

Here, "personController.js" is:

See this example:

Test it Now
Next TopicAngularJS Modules