0

I am facing a race condition. One of the service is changing the view using ui-router and then broadcasting event from $rootscope. The scope of the controller(tied to the changed view) is listening on this event, but whats happening is when the view is changed my controller scope is reinitialized and till the time it is ready the event has already been dispatched. So the new controller scope never listens for the event.

Please provide some way to handle this situation.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Nishant
  • 1,034
  • 9
  • 19

1 Answers1

0

What you can do is, Instead of listening for event in controller, listen for the event in a service. Since, service are bound to have only a single instance, you won't face such issue in service.

And, as for as the controller, you can first check for the presence of a flag in the service, then retrieve the updated value.

Consider this sample code taken from here.

app.factory('userService', ['$rootScope', function ($rootScope) {

    var service = {

        model: {
            name: '',
            email: ''
        },

        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;
}]);
Community
  • 1
  • 1
Gaurav
  • 3,614
  • 3
  • 30
  • 51