IT

AngularJS #8 - Controllers

금마s 2021. 12. 21. 22:40

✔ AngularJS Controllers

 > control the data of AngularJS applications

 > controllers are regular JavaScript Objects

 

1. AngularJS Controllers

 > AngularJS applications are controlled by controllers

 > 'ng-controller' directive defines the application controller

 > controller is a JavaScript Object, created by 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>
 Full Name: {{firstName + " " + lastName}}
</div>

<script>
 var app = angular.module('myApp', []);
 app.controller('myCtrl', function($scope) {
  $scope.firstName = "John";
  $scope.lastName = "Doe";
 });
</script>

 

2. Controller Methods

 > controller can also have methods (variables as functions)

<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>
 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>

 

3. Controllers In External Files

<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
 <li ng-repeat="x in names">
  {{x.name + ', ' + x.country}}
 </li>
</ul>
</div>

<script src="namesController.js"></script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
 $scope.names = [
  {name:'Jani', country:'Norway'},
  {name:'Hege', country:'Sweden'},
  {name:'Kai', country:'Denmark'}
 ];
});
728x90

'IT' 카테고리의 다른 글

AngularJS #10 - Filters  (0) 2021.12.26
AngularJS #9 - Scope  (0) 2021.12.22
AngularJS #7 - Data Binding  (0) 2021.12.21
AngularJS #6 - ng-model Directive  (0) 2021.12.19
AngularJS #5 - Directives  (0) 2021.12.18