Search code examples
angularjsangularjs-routingangularjs-rootscope

Route change events while trying to avoid using $rootScope


As the Angular team (and severals blogs) adviced, I try to avoid using $rootScope as possible in my apps.

$rootScope exists, but it can be used for evil

"Of course, global state sucks and you should use $rootScope sparingly, like you would (hopefully) use with global variables in any language. In particular, don't use it for code, only data. If you're tempted to put a function on $rootScope, it's almost always better to put it in a service that can be injected where it's needed, and more easily tested." - from Angular FAQ

But in one of my apps, I use several times events such as $routeChangeStart that are broadcast events using $rootScope:

/* Force redirection to home page when a connected user calls login page */
$rootScope.$on("$routeChangeStart", function(event, next, current) {
    if(next.$$route.originalPath == '/login' && Session.isUserConnected()) {
        $location.path("/home");
    }
}

I don't see a way to avoid $rootScope in these cases.

  • Is there a more elegant way to do this kind of tricks?
  • Is that a design error of my app to use it?
  • Must I resign myself to use it when absolutely necessary?

Tell me if you want me to provide more code samples.


Solution

  • You missread that. First of all, this event was added by Angular team - do you think they recommend not to use it?:D That article is about that you should not put everything to $rootScope, which seems to be an easy way for beginners.

    Actually, using $rootScope - for for global events is absolutely ok -- that is actual purpose of this service.