AngularJS - Kapsamlar

Kapsam, denetleyiciyi görünümlere bağlayan özel bir JavaScript nesnesidir. Kapsam, model verilerini içerir. Denetleyicilerde, model verilerine $ kapsam nesnesi aracılığıyla erişilir.

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

Aşağıdaki önemli noktalar yukarıdaki örnekte ele alınmıştır -

  • $ Kapsamı, yapıcı tanımı sırasında denetleyiciye ilk argüman olarak iletilir.

  • $ Kapsam.message ve $ kapsam.type HTML sayfasında kullanılan modellerdir.

  • Kontrolörü shapeController olan uygulama modülünde yansıtılan modellere değerler atıyoruz.

  • $ Kapsam içinde fonksiyonlar tanımlayabiliriz.

Kapsam Kalıtımı

Kapsam, denetleyiciye özeldir. İç içe geçmiş denetleyicileri tanımlarsak, alt denetleyici kendi üst denetleyicisinin kapsamını devralır.

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

Aşağıdaki önemli noktalar yukarıdaki örnekte ele alınmıştır -

  • ShapeController'da modellere değerler atıyoruz.

  • CircleController adlı alt denetleyicideki mesajı geçersiz kılıyoruz . CircleController adlı denetleyicinin modülünde mesaj kullanıldığında, geçersiz kılınan mesaj kullanılır.

Misal

Aşağıdaki örnek, yukarıda bahsedilen tüm direktiflerin kullanımını göstermektedir.

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>

Çıktı

Bir web tarayıcısında testAngularJS.htm dosyasını açın ve sonucu görün.