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 的控制器模块中使用消息时,将使用被覆盖的消息.
以下示例显示了所有上述指令的使用.
<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 并查看结果.