My service:

myApp.factory("MediaService", ['$http', 
function($http) {

    return {
        all: function() {
            return $http.get('/media');
        save: function( data ) {
            return $http.post('/media', data);

My controller:

myApp.controller("MediaController", ['$http', '$scope', '$routeParams', 'Upload', 'MediaService', 'messageService',  
function( $http, $scope, $routeParams, Upload, MediaService, messageService) {
    var media = this;

    MediaService.all().success( function (data) {
        media.versioning = []
        media.files = []
        for(i = 0, len = data[0].file.length; i< len; i++)
            if(!media.versioning[data[0].file[i].key[0]] || media.versioning[data[0].file[i].key[0]].version[0] < data[0].file[i].version[0])
                media.versioning[data[0].file[i].key[0]] = data[0].file[i]
        for(var value in media.versioning) 
            media.files.push( media.versioning[value] )

I want to move the code within .success() into the MediaService factory so I can re-use it in another controller.

Obviously I do not want to simply copy and paste this into the other controller, although that would work.

I tried to $q.defer/resolve within the service but it did not work (I believe that practice is deprecated).

What is the best way to move this logic into the service? Ideally I would like to be able to use media.files = MediaService.files().

  • 1
    \$\begingroup\$ Welcome to Code Review! Your title should be an explanation of what your code does, not a question about your code. You can put any concerns in the question body. You'll also want to read the Help Center. \$\endgroup\$
    – anon
    Commented Jun 24, 2015 at 15:26

1 Answer 1


You could define your 'service' on the service provider instead of the factory, or put one in between. Any property exposed on the service can be referenced in the controller, and whatever the service does with that property will be reflected in the controller. That's one of the differences between factory and service.

Take a look at this plunker for an example.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.