Angularjs-controllers

提供:Dev Guides
移動先:案内検索

AngularJS-コントローラー

AngularJSアプリケーションは、主にコントローラーを使用して、アプリケーション内のデータの流れを制御します。 コントローラーは、_ng-controller_ディレクティブを使用して定義されます。 コントローラーは、属性/プロパティ、および関数を含むJavaScriptオブジェクトです。 各コントローラーは、パラメーターとして$ scopeを受け入れます。これは、コントローラーが処理する必要があるアプリケーション/モジュールを参照します。

<div ng-app = "" ng-controller = "studentController">
   ...
</div>

ここでは、ng-controllerディレクティブを使用して、_studentController_という名前のコントローラーを宣言します。 次のように定義します-

<script>
   function studentController($scope) {
      $scope.student = {
         firstName: "Mahesh",
         lastName: "Parashar",

         fullName: function() {
            var studentObject;
            studentObject = $scope.student;
            return studentObject.firstName + " " + studentObject.lastName;
         }
      };
   }
</script>
  • studentControllerは、$ scopeを引数として持つJavaScriptオブジェクトとして定義されます。
  • $ scopeは、studentControllerオブジェクトを使用するアプリケーションを指します。
  • $ scope.studentは、studentControllerオブジェクトのプロパティです。
  • firstNameとlastNameは、$ scope.studentオブジェクトの2つのプロパティです。 それらにデフォルト値を渡します。
  • プロパティfullNameは、結合された名前を返す$ scope.studentオブジェクトの関数です。
  • fullName関数では、studentオブジェクトを取得してから、結合された名前を返します。
  • 注として、コントローラーオブジェクトを別のJSファイルに定義し、HTMLページでそのファイルを参照することもできます。

今、ng-modelを使用するか、次のように式を使用してstudentControllerのstudentプロパティを使用できます-

Enter first name: <input type = "text" ng-model = "student.firstName"><br>
Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
  • student.firstNameとstudent.lastnameを2つの入力ボックスにバインドしました。
  • student.fullName()をHTMLにバインドしました。
  • これで、姓と名の入力ボックスに何かを入力するたびに、フルネームが自動的に更新されるのを見ることができます。

次の例は、コントローラの使用を示しています-

testAngularJS

<html>
   <head>
      <title>Angular JS Controller</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>

      <div ng-app = "mainApp" ng-controller = "studentController">
         Enter first name: <input type = "text" ng-model = "student.firstName"><br>
         <br>
         Enter last name: <input type = "text" ng-model = "student.lastName"><br>
         <br>
         You are entering: {{student.fullName()}}
      </div>

      <script>
         var mainApp = angular.module("mainApp", []);

         mainApp.controller('studentController', function($scope) {
            $scope.student = {
               firstName: "Mahesh",
               lastName: "Parashar",

               fullName: function() {
                  var studentObject;
                  studentObject = $scope.student;
                  return studentObject.firstName + " " + studentObject.lastName;
               }
            };
         });
      </script>

   </body>
</html>

出力

ファイル_testAngularJS_をWebブラウザーで開き、結果を確認します。