pass the value from one page to another using rootscope in angularJS

1.8k Views Asked by At

Login.js:

app.controller('LoginFormController', ['$scope','$http','$rootScope', '$state', function($scope, $http, $rootScope, $state) {
    $scope.user = {};
    $scope.authError = null;
    $scope.login = function() {
      $scope.authError = null;

      var emailId = $scope.user.email;
      var password = $scope.user.password;
      $http({
        url: 'http://localhost:8090/login/login',
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'

        },
        data: 'email='+emailId+'&password='+password
        //data: {'email': $scope.user.email, 'password': $scope.user.password}
      }).then(function(response) {
        console.log(response.data);


        if (response.data.status == 'SUCCESS') {

          $scope.user = response.data.user.firstName;
          $rootScope.test = response.data.user.firstName;
          console.log("check: ",$rootScope.test)
          $state.go('app.dashboard');
        } else {
          //alert('invalid login');
          $scope.authError = 'Email or Password not right';
        }
      }, function(x) {
        $scope.authError = 'Server Error';
      })
    };
}])

I saved the value under $rootScope.test

Here Is my App.main.js:

'use strict';
  angular.module('app').controller('AppCtrl', ['$scope','$rootScope',
   function($scope, $rootScope) {

    $scope.user5 = $rootScope.test;

  }
 ]);

trying to print the rootscope

If I run this Code i am facing the error of $rootScope is undefined in the console. How to Resolve this

5

There are 5 best solutions below

1
sedhal On BEST ANSWER

$rootScope is the parent of all $scope, each $scope receives a copy of $rootScope data which you can access using $scope itself.

Here is a modified version https://jsfiddle.net/sedhal/g08uecv5/17/

angular.module('myApp', [])
.run(function($rootScope) {
    $rootScope.obj = {
      "name":"user1",
      "bdate":"18/11/1994",
      "city":"Ahmedabad"
    };
})
.controller('myCtrl', function($scope, $rootScope) {
      $scope.data = $rootScope.obj;
})
.controller('myCtrl2', function($scope, $rootScope) {
     $scope.data1 = $rootScope.obj;
});
1
SylvainF On

There is a useful answer to your question here: https://stackoverflow.com/a/18881189/9013688

Instead of passing directly your property on the $rootScope, you could emit an event which could be listened in an other part of your app like this:

if (response.data.status == 'SUCCESS') {
  $rootScope.$emit('user-logged', response.data.user.firstName)
}

And then:

$rootScope.$on('user-logged', function(event, data){ do something with your data })

Or you could use a service which is a good way to handle your data in all your app.

0
Naren Murali On

Please ensure that you take the advice of georgeawg, his suggestion seems to be the best way to implement this functionality in my opinion.

I want to suggest what might be wrong with your example.

If you can see that in the main App.main.js you have given the declaration as

angular.module('app').controller(...

But you are using a variable app in login.js like so.

app.controller(...

Which I am assuming you are creating somewhere else. Thus the set rootscope value is lost because there are two instances of the same app.


The solution to your problem will be to declare one variable app which will store the instance of the app. So the fix for your solution will be to modify App.main.js to be like so.

var app = angular.module('app');

app.controller(...

Also you need to remove any other arbitary var app = in your complete code, since these will create multiple instances of the same app.

I hope my explanation was understandable and the correct guess, please try out this solution!

0
Chaminda Jayanath Udawatte On

In your main js add this.

app.run(['$rootScope', function($rootScope) {
  $rootScope.test; 
}]);
0
BShaps On

Here is a sample implementation of george's suggestion which is the proper way to handle this.

app.controller('LoginFormController', ['$scope','$http','$rootScope', '$state', 'stateService', function($scope, $http, $rootScope, $state, stateService) {
    var userFirstName = 'John';
    stateService.setFirstName('Bill');

    userFirstName = stateService.getFirstName(); 
    console.log(userFirstName); // result will be 'Bill'
}])

And the service which I usually call stateService

app.factory('stateService', [factory]);

function factory() {        
    var userFirstName = null;

    stateService.getFirstName = function() {
        return userFirstName;
    };

    stateService.setFirstName = function(firstName) {
        userFirstName = firstName;
    };

    return stateService;
}