如何访问一个模块中定义$ rootScope值到另一个模块 [英] How to access $rootScope value defined in one module into another module

查看:204
本文介绍了如何访问一个模块中定义$ rootScope值到另一个模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要了解的我如何可以访问一个模块中定义到其他模块$ rootScope价值的价值?

下面是我的code:

的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

经过下面的例子,但没有工作:

Checked below example but did not work:

  • AngularJS $rootScope variable exists, but not accessible

推荐答案

明确注入'$范围,而不是'$ rootScope testCtrl ,所以刚才创建该控制器一个新的范围,无论使用该参数的名称作为第一个参数传递。

Explicitly inject '$scope', not '$rootScope' in testCtrl, so a new scope is created just for that controller and passed as the first argument regardless of the name used for that argument.

不正确的:

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

正确:

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

这篇关于如何访问一个模块中定义$ rootScope值到另一个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆