2

In my Angular app, I am consuming an API that delivers images in different sizes depending on the parameters I append to the image request (e.g. ?size=small or ?size=medium).

In order to make it easier for my views to directly request the image sizes they need, I would like to write a bunch of methods that can be called from any view across my app and would return the appropriate image URL.

I would like to be able to call methods as follows:

getSmallImage(myImageURL), getMediumImage(anotherImageURL) etc.

I have started writing a Factory for this as detailed below:

myApp.factory('imageService', function (imageURL){
    return {
         getSmallImage: function(imageURL) {
              // do stuff with imageURL
         }
         getMediumImage: function(imageURL) {
              // do stuff with imageURL
         }
    }
});

This works, but if my understanding of factories is correct, I still have to include the specific methods I want to call in my controller and wrap them in a separate controller method (e.g. as detailed in this post).

My very uneducated guess is that in this particular case, surely there is an easier way of making these methods directly available across views without having to repeat those methods in each controller? Or is this the recommended way of going about this, and if so, why?

Community
  • 1
  • 1
simonrohrbach
  • 512
  • 4
  • 17
  • What you *could* do is store the instanced service as a controller scope member, then your view could invoke the methods by accessing the scope variable. But I guess this is far from best-practice. – kasoban Jan 30 '14 at 12:34

1 Answers1

2

You can just put it on the $rootScope:

app.run(function($rootScope, imageService){
  $rootScope.getSmallImage = imageService.getSmallImage;
  $rootScope.getMediumImage = imageService.getMediumImage;
})
Ilan Frumer
  • 32,059
  • 8
  • 70
  • 84