目录

AngularJS - 范围( Scopes)

Scope是一个特殊的JavaScript对象,它将控制器与视图连接起来。 范围包含模型数据。 在控制器中,模型数据通过$ scope对象访问。

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

以上示例考虑了以下要点 -

  • $ scope在构造函数定义期间作为第一个参数传递给controller。

  • $ 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的控制器的模块中使用消息时,将使用被覆盖的消息。

例子 (Example)

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

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>

输出 (Output)

在Web浏览器中打开文件testAngularJS.htm并查看结果。

新页面打开
↑回到顶部↑
WIKI教程 @2018