Search code examples
angularjsangularjs-scopeangularjs-service

Recycling AngularJS functions


I am pretty new with AngularJS, but was wondering how to create commonly used functions outside the scope of a controller.

For example, I pretty often need to call a function to start a "Loading" spinner (for RESTful calls, etc). I tried adding a showLoadingModal() function as a service, but those only seem good for retrieving data from what I've seen. Do I have to add this function to all of my controllers, or can you create app-level functions somehow?


Solution

  • You could define your common method on $rootScope, which will be available via prototypical inheritance to any child scope in your application.

    Or, you could certainly define a service called "utilities" and just inject it wherever it's needed. Services are good for more than wrapping data-retrieval calls!

    Of these two approaches, I would recommend the latter. More testable and less pollution of $rootScope.