Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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

share|improve this question
1  
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. –  QPaysTaxes Jun 24 at 15:26

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
Thank you so much :) Now I can clean my code –  Colin Palmer Jun 30 at 8:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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