AngularJS 作用域(Scope)

时间:2022-06-19 21:35:53

AngularJS作用域(Scope)

Scope作用域是应用在视图和控制器之间的纽带,Scope是一个对象包含可用的方法和属性,Scope可以应用在试图和控制器上。

$scope是针对当前的controller的作用域生效

$rootScope是针对全局controller的作用域生效

下面使用代码进行这个作用域的演示

 <html>
<head>
<title>AngularJS作用域</title>
<meta charset="utf-8" />
<script src="js/angular.min.js"></script>
<style>
.frame {
height:250px;
border:1px solid black;
background-color:lightblue;
padding:10px;
margin:20px;
} </style>
</head>
<body ng-app="myApp">
<div class="frame" ng-controller="oneController">
scope1 :{{scope1}}<br />
rootScope1: {{rootScope1}}<br />
scope2 :{{scope2}}<br />
rootScope2 :{{rootScope2}}<br />
</div> <div class="frame" ng-controller="towController">
scope1 :{{scope1}}<br />
rootScope1: {{rootScope1}}<br />
scope2 :{{scope2}}<br />
rootScope2 :{{rootScope2}}<br />
</div> <script>
var app = angular.module("myApp", []);
app.controller("oneController", function ($scope,$rootScope) {
$scope.scope1 = "我是scope1";
$rootScope.rootScope1 = "我是rootScope1";
})
app.controller("towController", function ($scope, $rootScope) {
$scope.scope2 = "我是scope2";
$rootScope.rootScope2 = "我是rootscope2";
})
</script>
</body>
</html>