AngularJS 作用域Scopes
时间:2021-11-23 作者:匿名
Scope是一个特殊的JavaScript对象,它连接控制器和视图。 Scope包含模型数据。 在控制器,模型通过$Scope对象访问数据。
Scope是一个存储应用数据模型的对象。
Scope为 表达式 提供了一个执行上下文。
Scope作用域的层级结构对应于 DOM 树结构。
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。
产业范围
是controller-specific范围。 如果我们定义嵌套控制器,然后孩子控制器继承了其父的范围控制器。
<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://www.yangzhiw.cn/static/js/angularjs-1.5.8/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在web浏览器并查看结果。