Search code examples
angularjsangular-ui-routerrootscope

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


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


Solution

  • $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;
    });