Controllers manage AngularJS applications. The ng-controller directive specifies the application controller. A controller is a JavaScript object created using a 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 = angular.module(‘myApp’, []); app.controller(‘myCtrl’, function($scope) { $scope.firstName = “John”; $scope.lastName = “Doe”; }); </script> |
Application explained:
The AngularJS application is defined by ng-app=”myApp“, which allows it to run within the <div>.
The ng-controller=”myCtrl” attribute specifies the controller, and the myCtrl function is a JavaScript function that AngularJS calls with a $scope object that contains application variables and functions. The controller creates two properties, firstName and lastName, while the ng-model directives connect the input fields to these properties.