簡體   English   中英

使用angularjs中的$ rootScope將值從一個不同的應用程序模塊控制器傳遞到另一個應用程序模塊服務

[英]pass value from one different app module controller to another app module service using $rootScope in angularjs

我正在用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

請告訴我我做錯了什么

您可以為此目的使用本地存儲或會話存儲。

登錄控制器:

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

});

這是文檔鏈接: 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;
});

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM