详解AngularJS中的作用域
作者:bea
范围扮演其视图连接控制器的角色一个特殊的JavaScript对象。范围包含了模型数据。在控制器,模型数据通过$scope对象访问。 <script> var mainApp = angular.module("mainApp", []); mainApp.controller("shapeController", function($scope) { $scope.message = "In shape controller"; $sc
范围扮演其视图连接控制器的角色一个特殊的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设定模型的值。
- 我们覆盖的子控制器circleController消息。当“消息”内的控制器circleController的模块使用时,将用于重写的消息。
例子
下面的例子将展示上述所有指令。
testAngularJS.html
<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="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/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>
结果
在Web浏览器打开textAngularJS.html。看到结果如下。
猜你喜欢
您可能感兴趣的文章:
- javascript实现根据时间段显示问候语的方法
- javascript显示中文日期的方法
- 使用AngularJS制作一个简单的RSS阅读器的教程
- 使用AngularJS中的SCE来防止XSS攻击的方法
- 初步认识JavaScript函数库jQuery
- 用JavaScript显示浏览器客户端信息的超相近教程
- 浅谈Jquery核心函数
- $.extend 的一个小问题
- 纯js实现无限空间大小的本地存储
- JS实现当前页居中分页效果的方法
- javascript中Date()函数在各浏览器中的显示效果
- javaScript中Math()函数注意事项
- 理解Javascript的动态语言特性
- 你所不了解的javascript操作DOM的细节知识点(一)
- jQuery实现复选框批量选择与反选的方法
- 在Python中使用glob模块查找文件路径的方法
- 举例简介AngularJS的内部语言环境
- 详解AngularJS中自定义指令的使用
- 详解AngularJS中的依赖注入机制