Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$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

like image 430
jankoichi Avatar asked May 02 '13 05:05

jankoichi


1 Answers

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)

like image 123
Eduard Gamonal Avatar answered Sep 24 '22 06:09

Eduard Gamonal