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