The example above demonstrated a controller object with two properties: lastName and firstName.
Additionally, a controller can also include methods (functions stored as 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 = angular.module(‘myApp’, []); app.controller(‘personCtrl’, function($scope) { $scope.firstName = “John”; $scope.lastName = “Doe”; $scope.fullName = function() { return $scope.firstName + ” “ + $scope.lastName; }; }); </script> |
Controllers in external files are JavaScript functions defined outside of the main HTML document, allowing for better organization, modularity, and maintainability of AngularJS applications.
<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 src=”personController.js”></script> |