Karthik KM
Karthik KM

Reputation: 33

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

I am doing project in angularjs,my requirement is need to pass value from one different app module controller to another app module service using $rootScope

Here my part of code 

Login module and controller

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

});

here my app.js file

I injected the login module to another module

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

below i access the loggedInuser here

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

});

});

but in console i am getting message like

 undifined

please tell me where i did wrong

Upvotes: 0

Views: 685

Answers (2)

Jazib Bashir
Jazib Bashir

Reputation: 503

Here is the Doc Link: 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;
});

Hope It Helps!

Upvotes: 0

Dinesh Shah
Dinesh Shah

Reputation: 1233

you can use localstorage or sessionstorage for this purpose.

login Controller :

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

loggedin user :

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

});

Upvotes: 1

Related Questions