0

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

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

请告诉我哪里做错了

4

2 回答 2

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);

});
于 2016-08-31T07:31:45.527 回答
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;
});

希望能帮助到你!

于 2016-08-31T07:38:11.973 回答