【问题标题】:How to access $rootScope value defined in one module into another module如何将一个模块中定义的 $rootScope 值访问到另一个模块中
【发布时间】: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/$rootScopedocs.angularjs.org/guide/scope
  • 你能看看我的例子吗?我无法访问 $rootScope 的值。
  • "每个应用程序都有一个根作用域。所有其他作用域都是根作用域的后代作用域。" - “应用程序”是指“模块”。 $rootScope 是模块的根范围。控制器的$scope 是模块的子模块,也就是$rootScope。所以不,根据设计,您不能在模块之间共享$rootScope。但是,您可以初始化它 (stackoverflow.com/questions/18880737/…),也可以将其设置为服务中保留的某个值,如副本中所述。

标签: angularjs angularjs-scope


【解决方案1】:

testCtrl 中显式注入'$scope',而不是'$rootScope',因此仅为该控制器创建一个新范围并作为第一个参数传递,而不管该参数使用的名称如何。

不正确:

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

正确:

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

【讨论】:

    【解决方案2】:

    这是您更新的工作Plunkr

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

    你还在&lt;head&gt;标签上设置了testCtlr,不知道是不是故意的。

    【讨论】:

      猜你喜欢
      • 2022-10-09
      • 1970-01-01
      • 2017-05-14
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多