3
\$\begingroup\$

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

ferada
11.4k25 silver badges65 bronze badges
asked Jun 24, 2015 at 15:25
\$\endgroup\$
1
  • 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\$ Commented Jun 24, 2015 at 15:26

1 Answer 1

1
\$\begingroup\$

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
answered Jun 28, 2015 at 18:41
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.