- 当前作用域介绍
作用域其实就像一个容器,作用域提供了基于原型链继承其父作用域属性的机制,先在该层范围内寻找数据模型,如果没有找到就要去父级作用域去找,直到找到最顶层rootscope为止,最顶层rootscope的标志就是在DOM 标签中有ng-app那一层,一般是在html标签中设置,如果想在网页的局部应用angularJS,那就在指定的DOM标签中,下面是我做测试的代码
html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/angular-1.5.8/angular.js"></script>
</head>
<body>
<div ng-app="myApp">
<div style="background-color: yellow;" ng-controller="ParentController">
<p>We can access:{{rootProperty}} and {{parentProperty}}</p>
<div style="background-color: red;" ng-controller="ChildController">
<p>
we can access:
{{rootProperty}}
and
{{parentProperty}}
and
{{childProperty}}
</p>
<p>{{fullSentenceFromChild}}</p>
</div>
</div>
</div>
<script src="js/app.js"></script>
</body>
</html>
js部分:
var myapp=angular.module('myApp',[]);
myapp.run(function ($rootScope) {
$rootScope.rootProperty='这是根作用域';
})
.controller('ParentController',function($scope) {
$scope.parentProperty='这是父亲';
})
.controller('ChildController',function ($scope) {
$scope.childProperty='这是孩子';
$scope.fullSentenceFromChild='Same $scope: we can access ' + $scope.rootProperty + ' and ' + $scope.parentProperty + ' and ' +
$scope.childProperty
});
测试结果是
我把childController移到外面后
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/angular-1.5.8/angular.js"></script>
</head>
<body>
<div ng-app="myApp">
<div style="background-color: yellow;" ng-controller="ParentController">
<p>We can access:{{rootProperty}} and {{parentProperty}}</p>
</div>
<div style="background-color: red;" ng-controller="ChildController">
<p>
we can access:
{{rootProperty}}
and
{{parentProperty}}
and
{{childProperty}}
</p>
<p>{{fullSentenceFromChild}}</p>
</div>
</div>
<script src="js/app.js"></script>
</body>
</html>
结果是