$rootScope vs. service - Angular JS

What is the difference between implementing a $rootScope function and a service? Security wise or performance wise.

I have read this, so I am wondering.

I have been trying to figure out whether or not a certain global function for my app would be best implemented in a service or on the $rootScope itself. To pitch you guys with an idea of what I am making, I'm currently developing a dirty form function in which it prompts the user if he/she navigates away from a certain form. In this case, I decided to best implement it as a global function, so any hints?

Thanks for the responses,

Jan

Answers:

Answer

In this case I would go for a service to avoid having a global state. all new scopes are created from $rootScope. New controllers or whoever uses a scope will have values of $rootscope available. For instance, if you define $rootScope.validate() and in a controller you define a function $scope.validate() because you forget about the first definition, something will certainly go wrong.

There is an article by Misko H. about this http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/

Services are instantianted on demand, whereas $rootScope is created during bootstrap, and can be injected wherever you need them. This is good for testability.

Angular won't instantiate services unless they are requested directly or indirectly by the application.

(http://docs.angularjs.org/guide/dev_guide.services.creating_services)

Answer

As @egamonal mentioned Services are more robust way to share common functionality. Not only services are instantiated on demand, they are singleton by nature so once a service gets created, the same instance gets passed around by AngularJS whenever requested. So if something can go on root scope, it can also be implemented using a service.

One think to keep in mind using such global approach is the possibility on memory leak. Instance of JS classes or maybe DOM elements remain in the memory because you have referenced them from you global functions (either in $rootscope or service).

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.