- 當(dāng)前作用域介紹
作用域其實(shí)就像一個(gè)容器,作用域提供了基于原型鏈繼承其父作用域?qū)傩缘臋C(jī)制祝高,先在該層范圍內(nèi)尋找數(shù)據(jù)模型恬偷,如果沒(méi)有找到就要去父級(jí)作用域去找失乾,直到找到最頂層rootscope為止宪哩,最頂層rootscope的標(biāo)志就是在DOM 標(biāo)簽中有ng-app那一層娩贷,一般是在html標(biāo)簽中設(shè)置第晰,如果想在網(wǎng)頁(yè)的局部應(yīng)用angularJS锁孟,那就在指定的DOM標(biāo)簽中彬祖,下面是我做測(cè)試的代碼
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
});
測(cè)試結(jié)果是
我把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>
結(jié)果是