我需要了解" 如何将一个模块中定义的$ 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
检查以下示例但不起作用:
答案 0 :(得分:3)
在'$scope'
中明确注入'$rootScope'
,而不是testCtrl
,因此只为该控制器创建一个新范围,并将其作为第一个参数传递,而不管该参数使用的名称是什么。 / p>
不正确:
testapp.controller('testCtrl', ['$scope',
function($rootScope) {
$rootScope.root = "Root Scope Param1";
}
]);
正确:
testapp.controller('testCtrl', ['$rootScope',
function($rootScope) {
$rootScope.root = "Root Scope Param1";
}
]);
答案 1 :(得分:2)