Angularjs-scopes

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

AngularJS-スコープ

スコープは、コントローラーをビューに接続する特別なJavaScriptオブジェクトです。 スコープにはモデルデータが含まれます。 コントローラでは、$ scopeオブジェクトを介してモデルデータにアクセスします。

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

   mainApp.controller("shapeController", function($scope) {
      $scope.message = "In shape controller";
      $scope.type = "Shape";
   });
</script>

上記の例では、次の重要な点が考慮されます-

  • $ scopeは、コンストラクターの定義中にコントローラーの最初の引数として渡されます。
  • $ scope.messageと$ scope.typeは、HTMLページで使用されるモデルです。
  • コントローラーがshapeControllerであるアプリケーションモジュールに反映されるモデルに値を割り当てます。
  • $ scopeで関数を定義できます。

スコープの継承

スコープはコントローラー固有です。 ネストされたコントローラーを定義すると、子コントローラーは親コントローラーのスコープを継承します。

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

   mainApp.controller("shapeController", function($scope) {
      $scope.message = "In shape controller";
      $scope.type = "Shape";
   });
   mainApp.controller("circleController", function($scope) {
      $scope.message = "In circle controller";
   });

</script>

上記の例では、次の重要な点が考慮されます-

  • shapeControllerのモデルに値を割り当てます。
  • _circleController_という名前の子コントローラーのメッセージをオーバーライドします。 _circleController_という名前のコントローラーのモジュール内でメッセージが使用される場合、オーバーライドされたメッセージが使用されます。

次の例は、上記のすべてのディレクティブの使用を示しています。

testAngularJS

<html>
   <head>
      <title>Angular JS Forms</title>
   </head>

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

      <div ng-app = "mainApp" ng-controller = "shapeController">
         <p>{{message}} <br/> {{type}} </p>

         <div ng-controller = "circleController">
            <p>{{message}} <br/> {{type}} </p>
         </div>

         <div ng-controller = "squareController">
            <p>{{message}} <br/> {{type}} </p>
         </div>

      </div>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>

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

         mainApp.controller("shapeController", function($scope) {
            $scope.message = "In shape controller";
            $scope.type = "Shape";
         });
         mainApp.controller("circleController", function($scope) {
            $scope.message = "In circle controller";
         });
         mainApp.controller("squareController", function($scope) {
            $scope.message = "In square controller";
            $scope.type = "Square";
         });

      </script>

   </body>
</html>

出力

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