AngularJS controller is used to control the data of AngularJS applications.
AngularJS controller is an ordinary JavaScript object.
AngularJS controller
AngularJS applications are controlled by the controller.
The ng-controller directive defines an application controller.
A controller is a JavaScript object, which can be created through the standard JavaScript object constructor.
<div ng-app="myApp" ng-controller="myCtrl"> First Name: <input type="text" ng-model="firstName"><br> Last Name: <input type="text" ng-model="lastName"><br> <br> Full Name: {{firstName + " " + lastName}} </div> <script> var app = ('myApp', []); ('myCtrl', function($scope) { $ = "John"; $ = "Doe"; }); </script>
Code explanation:
AngularJS application is defined by ng-app="myApp". The effective scope of this application is in the <div> where the ng-app is located.
The ng-controller="myCtrl" property is an AngularJS directive that defines a controller.
The myCtrl function is a normal JavaScript function.
AngularJS uses the $scope object to call the controller.
In AngularJS, $scope is an application object (i.e. the owner of application variables and functions).
The controller contains two properties (or variables): firstName and lastName. They are attached to the $scope object.
The ng-model directive binds the value of the input tag to the controller's properties (firstName and lastName).
Controller method
The above example shows that the controller object contains two properties: lastName and firstName.
The controller can also include methods (assigning functions to variables):
<div ng-app="myApp" ng-controller="personCtrl"> First Name: <input type="text" ng-model="firstName"><br> Last Name: <input type="text" ng-model="lastName"><br> <br> Full Name: {{fullName()}} </div> <script> var app = ('myApp', []); ('personCtrl', function($scope) { $ = "John"; $ = "Doe"; $ = function() { return $ + " " + $; } }); </script>
Put the controller in an external file
In large applications, controller code is often written in external files.
Copy the code from the <script> tag to an external file:
<div ng-app="myApp" ng-controller="personCtrl"> First Name: <input type="text" ng-model="firstName"><br> Last Name: <input type="text" ng-model="lastName"><br> <br> Full Name: {{firstName + " " + lastName}} </div> <script src=""></script>
Another example
Create a new controller file and name it:
('myApp', []).controller('namesCtrl', function($scope) { $ = [ {name:'Jani',country:'Norway'}, {name:'Hege',country:'Sweden'}, {name:'Kai',country:'Denmark'} ]; });
Then use this controller file in the application:
<div ng-app="myApp" ng-controller="namesCtrl"> <ul> <li ng-repeat="x in names"> {{ + ', ' + }} </li> </ul> </div> <script src=""></script>
The above is the entire content of this article, I hope you like it.