scope是什么
scope是html和单个controller之间的桥梁,数据绑定就靠他了。rootscope是各个controller中scope的桥梁。用rootscope定义的值,可以在各个controller中使用。
scope的生命周期
-
创建
-
在创建控制器或指令时,AngularJS会用 $injector 创建一个新的作用域,并在这个新建的控
制器或指令运行时将作用域传递进去
链接
-
当Angular开始运行时,所有的 scope 对象都会附加或者链接到视图中。所有创建 $scope 对
象的函数也会将自身附加到视图中。这些作用域将会注册当Angular应用上下文中发生变化时需
要运行的函数。
更新
-
当事件循环运行时,它通常执行在顶层
scope对象上(被称作
rootScope ),每个子作用域
都执行自己的脏值检测。每个监控函数都会检查变化。如果检测到任意变化, $scope 对象就会触
发指定的回调函数
销毁
- 当一个 scope在视图中不再需要时,这个作用域将会清理和销毁自己。尽管永远不会需要清理作用域(因为Angular会为你处理),但是知道是谁创建了这个作用域还是有用的,因为你可以使用这个 scope 上叫做 $destory() 的方法来清理这个作用域
下面用实例详细的说明一下
js代码
phonecatApp.controller('TestCtrl',['$scope','$rootScope',
function($scope,$rootScope) {
$rootScope.name = 'this is test';
}
]);
phonecatApp.controller('Test111Ctrl',['$scope','$rootScope',
function($scope,$rootScope) {
$scope.name = $rootScope.name;
}
]);
html代码
<div ng-controller="TestCtrl">
I set the global variable.<strong>{{$root.name}}</strong>
</div>
<div ng-controller="Test111Ctrl">
1,get global variable .<strong>{{name}}</strong><br>
2,get global variable .<strong>{{$root.name}}</strong>
</div>
结果显示
I set the global variable.this is test
1,get global variable .this is test
2,get global variable .this is test
由结果可以看出来,$rootScope.name设置的变量,在所有controller里面都是可以直接用{{$root.name}}来显示的,很强大。那当然也可以赋值给scope.