$rootScope vs. service - Angular JS

2020-01-29 07:09发布

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

2条回答
家丑人穷心不美
2楼-- · 2020-01-29 07:50

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).

查看更多
Summer. ? 凉城
3楼-- · 2020-01-29 08:07

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)

查看更多
登录 后发表回答