AngularJS - ขอบเขต

ขอบเขตเป็นวัตถุ JavaScript พิเศษที่เชื่อมต่อคอนโทรลเลอร์กับมุมมอง ขอบเขตประกอบด้วยข้อมูลแบบจำลอง ในคอนโทรลเลอร์ข้อมูลโมเดลจะถูกเข้าถึงผ่านวัตถุ $ ขอบเขต

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

ประเด็นสำคัญต่อไปนี้ได้รับการพิจารณาในตัวอย่างข้างต้น -

  • ขอบเขต $ ถูกส่งผ่านเป็นอาร์กิวเมนต์แรกไปยังคอนโทรลเลอร์ในระหว่างการกำหนดคอนสตรัคเตอร์

  • $ 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.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>

เอาต์พุต

เปิดไฟล์testAngularJS.htmในเว็บเบราว์เซอร์และดูผลลัพธ์