I've created maybe five services like RoleService, AuthService, etc. Each of them has some state (e.g., RoleService.role, AuthService.isLoggedIn) affecting a lot of controllers and some other services and directives.

Sometimes I need to $watch the variable, so my hacky solution was to put the whole service in the $scope of the controllers which need it. I even put one of the services on the $rootScope, which makes feel me bad, but it was very practical.

What's the best practice for watching service state?

Now I've got the idea to create a BaseService as a data container for all the (maybe five) interesting variables. There would be no methods, as they belong to the services where they're now. This doesn't sound like OO, but it simplifies things and removes dependencies between services:

All of them would depend on the BaseService and be otherwise independent. It won't hurt testing as BaseService is trivial to fill with data. I can't see any downsides, but it doesn't feel quite right.

Is this a good idea? What better alternatives exists?

Nobody answered, so I tried it and it works well, despite BaseService aggregating unrelated variables. A theoretically cleaner solution could be to create a data holder for every service, something like RoleService + RoleHolderService, AuthService + AuthStateHolderService, etc. Now, the holders would depend on nothing and their content must be treated as read-only by everything besides their corresponsing service, i.e., RoleHolderService.role may be written by the RoleHolderService only.

Practically, aggregating all the holders into a single service is no problem. The information if a program part wants to read the user's role or if it's logged in is lost, but it's no big loss as there are so many such readers. Controllers and services changing such state do this only via a method of the corresponding service (e.g., AuthService.login).


This is really a good question, I have come across this thread which is related to your problem https://stackoverflow.com/a/14056952/1478077 but still injecting $rootScope into the factory looks a little hacky solution because $broadcasting event on $rootScope would be a expensive operation, I think https://davidwalsh.name/customevent we can just dispatch the custom event on Angular Factory I didn't try them myself, but I think this could work, so the event can be dispatch on the Angular factory and in this way factory can register and listen the event in each controller.

Hope this will also help you to solve your problem. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.