使用angularjs中的$ rootScope将值从一个不同的app模块控制器传递到另一个app模块服务

时间:2016-08-31 07:14:33

标签: angularjs routes angular-ui-router angular-module angular-route-segment

我在angularjs中做项目,我的要求是需要使用$ rootScope将值从一个不同的app模块控制器传递到另一个app模块服务

Here my part of code 

登录模块和控制器

 var loginApp = angular.module('loginApp', [ 'ngCookies' ]);

 loginApp.controller('loginCtrl', function($scope, $cookies,    $cookieStore,
    $rootScope) {
$scope.redirect = function() {
    if ($scope.name == 'admin' && $scope.password == 'admin') {
        $rootScope.loggedInUser = $scope.name;
        window.location = "pages/index.html";
    } else
        alert('User / Password Invalid');
} 

});

这是我的app.js文件

我将登录模块注入另一个模块

  var smartCities = angular.module('smartCities', [ 'ngRoute', 'ngAnimate',
    'ui.bootstrap', 'ngTouch', 'ui.grid.exporter', 'ui.grid',
    'ui.grid.selection', 'ui.grid.autoResize', 'ngCookies', 'loginApp' ]);

下面我在这里访问loggedInuser

 smartCities.run(function($rootScope, $location, $cookies, $cookies,
    $cookieStore) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
    console.log($rootScope.loggedInUser);
    $location.path(next.$$route.originalPath);

});

});

但是在控制台中我收到了像

这样的消息
 undifined

请告诉我我哪里做错了

2 个答案:

答案 0 :(得分:1)

您可以将localstorage或sessionstorage用于此目的。

登录控制器:

 loginApp.controller('loginCtrl', function($scope, $cookies,    $cookieStore,
    $rootScope) {
 $scope.redirect = function() {
if ($scope.name == 'admin' && $scope.password == 'admin') {
    localStorage.loggedInUser = $scope.name;
    window.location = "pages/index.html";
} else
    alert('User / Password Invalid');
} 

登录用户:

 smartCities.run(function($rootScope, $location, $cookies, $cookies,
$cookieStore) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log(localStorage.loggedInUser);
$location.path(next.$$route.originalPath);

});

答案 1 :(得分:0)

以下是文档链接:https://docs.angularjs.org/api/ng/type/angular.Module#value

//this is one module
var myUtilModule = angular.module("myUtilModule", []);

// this is value to be shared among modules, it can be any value
myUtilModule.value  ("myValue"  , "12345");

//this is another module
var myOtherModule = angular.module("myOtherModule", ['myUtilModule']);

myOtherModule.controller("MyController", function($scope, myValue) {
      // myValue of first module is available here
}

myOtherModule.factory("myFactory", function(myValue) {
    return "a value: " + myValue;
});

希望它有帮助!