$范围和$ rootScope的区别 [英] Difference between $scope and $rootScope
问题描述
任何人都可以解释$范围和$ rootScope区别?
我觉得
$范围:
我们可以利用这个得到从特定页面特定控制器NG-模型属性。
块引用>$ rootScope
我们可以通过使用此得到来自任何页面的任何控制器的所有NG-模型属性。
块引用>这是正确的?还是别的什么?
解决方案的主要区别是与对象分配属性的可用性。以$范围分配的属性不能定义它,而与$ rootScope分配的属性可以在任何地方使用的控制器之外使用。
例如:如果在这个例子中你用$范围的部门属性将不会在第二个从第一控制器填充替换$ rootScope
\r\r\r\rangular.module(示例,[])\r
.controller('GreetController',['$范围,$ rootScope',\r
功能($范围,$ rootScope){\r
$ scope.name ='世界';\r
$ rootScope.department ='角';\r
}\r
])\r
.controller('ListController',['$范围',\r
功能($范围){\r
$ scope.names = ['伊戈尔','MISKO','Vojta开发'];\r
}\r
]);\r
&LT;脚本SRC =https://ajax.googleapis.com/ajax /libs/angularjs/1.2.23/angular.min.js\"></script>\r
\r
&LT;机身NG-应用=榜样&GT;\r
&LT; DIV CLASS =显示范围的-演示&GT;\r
&LT; DIV NG控制器=GreetController&GT;\r
您好{{名}}!\r
&LT; / DIV&GT;\r
&LT; DIV NG控制器=ListController&GT;\r
&LT;&OL GT;\r
&LT;李NG重复=名称名称&GT; {{名}}从{{}部门}&LT; /李&GT;\r
&LT; / OL&GT;\r
&LT; / DIV&GT;\r
&LT; / DIV&GT;\r
&LT; /身体GT;\r
Can anyone explain the difference between $scope and $rootScope?
I think
$scope:
We can get ng-model properties in particular controller from the particular page by using this.
$rootScope
We can get all ng-model properties in any controller from any page by using this.
Is this correct? Or anything else?
解决方案The main difference is the availability of the property assigned with the object. A property assigned with $scope cannot be used outside the controller in which it is defined whereas the a property assigned with $rootScope can be used anywhere.
Example: If in the example you replace $rootScope with $scope the department property will not be populated from the first controller in the second one
angular.module('example', []) .controller('GreetController', ['$scope', '$rootScope', function($scope, $rootScope) { $scope.name = 'World'; $rootScope.department = 'Angular'; } ]) .controller('ListController', ['$scope', function($scope) { $scope.names = ['Igor', 'Misko', 'Vojta']; } ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="example"> <div class="show-scope-demo"> <div ng-controller="GreetController"> Hello {{name}}! </div> <div ng-controller="ListController"> <ol> <li ng-repeat="name in names">{{name}} from {{department}}</li> </ol> </div> </div> </body>
这篇关于$范围和$ rootScope的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!