How to access $rootScope value defined in one modu

2019-09-01 09:45发布

问题:

I need to understand "How can I access the value of $rootScope value defined in one module into other module?"

Below is my 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";
  }
]);

Live demo : http://plnkr.co/edit/X0aamCi9ULcaB63VpVs6?p=preview

Checked below example but did not work:

  • AngularJS $rootScope variable exists, but not accessible

回答1:

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.

Incorrect:

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

Correct:

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


回答2:

Here is your updated working Plunkr

Basically I prefer to use $scope.$root to prevent the injection of the $rootScope.

You have also set the testCtlr on the <head> tag, don't know if it was on purpose or not.