AngularJS 范围


Scope 是一个特殊的 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 中为模型赋值。

  • 我们在名为的子控制器中覆盖消息 圆形控制器 .在名为的控制器模块中使用消息时 圆形控制器 ,使用被覆盖的消息。

例子


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

测试AngularJS.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>

输出


打开文件 测试AngularJS.htm 在网络浏览器中查看结果。