AngularJS的$rootScope和$scope联系和区别

时间:2022-06-06 09:09:48

  scope是html和单个controller之间的桥梁,数据绑定就靠他了。

  rootscope是各个controller中scope的桥梁。用rootscope定义的值,可以在各个controller中使用。

  直接上代码

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>scope</title>
<script src="../js/angular.js"></script>
</head> <body>
<div ng-controller="TestCtrl">
$root.name是<strong>{{$root.name}}</strong>
</div> <div ng-controller="Test111Ctrl">
$root.name是<strong>{{name}}</strong><br>
$scope.name是<strong>{{$root.name}}</strong>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('TestCtrl',function($scope,$rootScope) {
$rootScope.name = 'this is test';
}
); app.controller('Test111Ctrl',function($scope,$rootScope) {
$scope.name = $rootScope.name;
}
);
</script>
</body> </html>

注意一点:在html代码里面用$root取$rootScope的属性方法