Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

I'm trying to make a service that's polymorphic based upon what mode is specified in the URL. If the char param in the route is set to 'p', I want to use a PresentMode service. If the char param is set to 'n', I want to use a NoteMode service. Each of these present the same interface, but I want to choose one at a time.

So far the best solution I've come up with is something like this:

var mod = angular.module('modeModule', []);

mod.service('modeService', function($routeParams, presentMode, noteMode) {
  if ($routeParams.char === 'p') {
    this.mode = presentMode;
  } else if ($routeParams.char === 'n') {
    this.mode = noteMode;
  }
}

mod.service('presentMode', function() {});
mod.service('noteMode', function() {});

This works, but it requires that I append .mode to the end of every access (eg modeService.mode.blah(). Is there a better way to do this?

share|improve this question
1  
I think selection of appropriate service is injector's responsibility. Have you looked at $injector? Maybe it is possible to intercept service resolution requests. –  voroninp Dec 24 '14 at 23:27
1  
Or you can use service as a factory of the final service. –  voroninp Dec 24 '14 at 23:43

1 Answer 1

I don't understand what you'd like to have happen. You'll get a lot more traction on this question on the regular stackoverflow.

There's a lot of different styles to go about this. Personally, I keep my services clear of logic and just use them to wrangle data and as a central api. in my controllers, those data and api methods get scoped to the view. When I need to do some logic on the data or method, I'll use an angular decorator or filter.

To sum up my way, Services - data and methods Controllers - $scopes and $watchers (this is where you can set $scope.exMethod = exService.exMethod() and then just call exMethod() in your html) Filters / Decorators - business logic (put your if logics here)

share|improve this answer

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.