2014-05-23 63 views
0

我需要了解“如何访问一个模块中定义的$ 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

可能的[AngularJS Modules/Scope Sharing]重复(http://stackoverflow.com/questions/20751172/angularjs-modules-scope-sharing) –

+0

@Sergiu Paraschiv:我不认为这是重复的。我想在我的例子中访问$ rootScope的值而不是$ scope。 –

+0

同样的事情。任何地方的$ scope都是$ rootScope树的一部分。阅读https://docs.angularjs.org/api/ng/service/$rootScope和https://docs.angularjs.org/guide/scope –

回答

3

显式注入'$scope',而不是,所以为该控制器创建一个新的作用域,并作为第一个参数传递,而不管该参数使用的名称如何。

错误:

testapp.controller('testCtrl', ['$scope', 
    function($rootScope) { 
    $rootScope.root = "Root Scope Param1"; 
    } 
]); 

正确:

testapp.controller('testCtrl', ['$rootScope', 
    function($rootScope) { 
    $rootScope.root = "Root Scope Param1"; 
    } 
]); 
+0

非常感谢,现在它工作。 –

2

这里是你更新的工作Plunkr

基本上我更喜欢使用$scope.$root防止$rootScope的注入。

您还对<head>标记设置了testCtlr标记,不知道它是否有意或无意。

相关问题