【发布时间】:2014-07-12 13:55:36
【问题描述】:
我需要了解“如何将一个模块中定义的 $rootScope 值的值访问到另一个模块中?”
下面是我的代码:
Index.html
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"> </script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="test.js"></script>
</head>
<div ng-controller="serviceDIController">
Service Values is : <b> {{sdiParam}} </b> <br/>
Factory Values is : <b> {{fdiParam}} </b> <br/>
Root Scope Values is : <b> {{rootParam}} </b>
</div>
</html>
script.js
var app = angular.module("myapp", ['testModule']);
app.controller('serviceDIController',['$scope','$rootScope',
'testService','testFactory',function($scope, $rootScope,testService, testFactory)
{
$scope.sdiParam = testService.param;
$scope.fdiParam = testFactory.fparam;
// $scope.rootParam = $rootScope.root; // How to access "$rootScope.root" value defined in test.js in current module inside a controller?
}
]);
test.js
var testapp = angular.module("testModule", []);
testapp.service('testService', function() {
this.param = "Service Param1 DI";
});
testapp.factory('testFactory', function() {
var fact = {};
fact.fparam = "Fact Param1 DI";
return fact;
});
testapp.controller('testCtrl', ['$scope',
function($rootScope) {
$rootScope.root = "Root Scope Param1";
}
]);
现场演示:http://plnkr.co/edit/X0aamCi9ULcaB63VpVs6?p=preview
检查了下面的例子但没有用:
【问题讨论】:
-
@Sergiu Paraschiv :我不认为这是重复的。在我的示例中,我想访问 $rootScope 而不是 $scope 的值。
-
同样的事情。任何地方的任何
$scope都是$rootScope树的一部分。阅读docs.angularjs.org/api/ng/service/$rootScope 和docs.angularjs.org/guide/scope -
你能看看我的例子吗?我无法访问 $rootScope 的值。
-
"每个应用程序都有一个根作用域。所有其他作用域都是根作用域的后代作用域。" - “应用程序”是指“模块”。
$rootScope是模块的根范围。控制器的$scope是模块的子模块,也就是$rootScope。所以不,根据设计,您不能在模块之间共享$rootScope。但是,您可以初始化它 (stackoverflow.com/questions/18880737/…),也可以将其设置为服务中保留的某个值,如副本中所述。