不难理解, rootscope类似于js中的全局变量、 scope类似于局部变量
var a=1; function fn(a) { a=3; //a是函数的参数 } fn(2); console.log(a);//1 var tt = 'aa'; function test(){ alert(tt); //undifined var tt = 'dd'; alert(tt); //'dd'; } test();1.编译过程
在js的编译过程中,只是将变量声明和函数声明加到词法作用域,但是不进行赋值,在函数中声明的变量会添加到函数的局部作用域中
2.执行过程 在js的编译过程中,因为js是单线程的所以从上往下执行。 第一个aleart
alert(tt); //undefined因为在js的编译过程中已经将tt添加到函数的词法环境中,所以在执行时先去函数本身的词法作用域中找是否存在变量tt,因为此时还没有执行var tt = ‘dd’; 所以输出undifined。
$rootScope针对全局的作用域生效
$scope只针对当前的controller作用域生效
js的代码如下:
var angular=angular.module('myApp',[]); angular.controller('fiscontroller',function ($rootScope,$scope) { $rootScope.message='global'; //message在全局中有效 $scope.message1='fiscontroller'; }); angular.controller('seccontroller',function ($rootScope,$scope) { $scope.message2='seccontroller'; console.log($rootScope.message); })html视图的代码如下:
<!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="js/angular.js"></script> </head> <body> <div>{{message}}</div> <div ng-controller="fiscontroller">{{message1}} <span>{{message}}</span> </div> <div ng-controller="seccontroller">{{message2}} <span>{{message}}</span> </div> </body> </html>