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 的子控制器中覆蓋了 message。當在名為 circleController 的控制器的模組中使用 message 時,將使用覆蓋的 message。

示例

以下示例顯示了所有上述指令的使用。

testAngularJS.htm

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

輸出

在 Web 瀏覽器中開啟 testAngularJS.htm 檔案,檢視結果。

廣告