0
Uncaught ReferenceError: $rootScope is not defined

I have a form and on submit button, I am trying to store data in localStorage.

I found this below solution here: How do I store data in local storage using Angularjs?

not sure what or where I am going wrong.

Below is the related code.

contact.component.js

angular.module('myApp')
  .component('contactComponent', {
  restrict: 'E',
  $scope:{},    
  templateUrl:'contact/contact.html',
  controller: contactController,
  controllerAs: 'vm',
  factory:'userService',
  $rootscope:{}
});

function contactController($scope, $state,userService,$rootScope) {
  $scope.navigate = function(home){
    $state.go(home)
  };

  $scope.user = userService;
};

function userService($rootScope) {
  var service = {
    model: {
        name: '',
        email: '',
        query:''
    },
    SaveState: function () {
        sessionStorage.userService = angular.toJson(service.model);
    },
    RestoreState: function () {
        service.model = angular.fromJson(sessionStorage.userService);
    }
  }
  $rootScope.$on("savestate", service.SaveState);
  $rootScope.$on("restorestate", service.RestoreState);
  return service;
};

$rootScope.$on("$routeChangeStart", function (event, next, current) {
  if (sessionStorage.restorestate == "true") {
      $rootScope.$broadcast('restorestate'); //let everything know we need to restore state
      sessionStorage.restorestate = false;
  }
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
  $rootScope.$broadcast('savestate');
};
Nauman
  • 894
  • 4
  • 14
  • 45
  • which line is throwing the error – Sajeetharan Jan 31 '18 at 12:13
  • Because you did something that makes no sense at all, you've defined a `userService` as a factory and you're using `$rootScope` as argument but you're not passing it anywhere so when you try using it it's `undefined` it's perfectly logical... go check how to use `Services` and `Factories` in AngularJS: https://docs.angularjs.org/guide/services – anteAdamovic Jan 31 '18 at 12:15
  • 1
    `$rootScope.$on("$routeChangeStart",` is outside of any service / controller – Aleksey Solovey Jan 31 '18 at 12:18

0 Answers0