0

This is my code that currently works:

angular.module('myApp')
  .controller('myCtrl', function (DocumentTypeManagerPdf, DocumentTypeManagerVideo) {

    $scope.showPreview = function(document){
      var previewModule = eval('DocumentTypeManager' + document.clientModule);
      previewModule.show(document);
    };

  });

but... two things I would avoid:

  1. Eval is evil
  2. I am forced to inject every DocumentTypeManagerXYZ that I'll implement

In there a better solution tu use a Factory dynamically?

2 Answers 2

2

I think you should go with a factory pattern.

One service DocumentTypeManagerFactory

With one method like

var myDocumentTypeManager = DocumentTypeManagerFactory.instanciateWithType(document.clientModule);

myDocumentTypeManager.show(document);

Your controller will only inject one service (and the DocumentTypeManagerFactory should inject all)

In your DocumentTypeManagerFactory you should make a switch or if/else to avoid eval.

Sign up to request clarification or add additional context in comments.

Comments

1

I think you can use arguments in the function. inJS every function has a variable named arguments which is a array of given parameters.

But I am not sure how your DocumentTypeManagerXYZ objects are structured. So just type debugger; beginning of your controller function and check arguments data by console then you can take a correct action.

the below one is the first one comes to my mind;

var previewModule;
for(var i = 0, len=arguments.lengh; i <len; i++) {
   if (arguments[i].constructure.name === 'DocumentTypeManager' + document.clientModule) {
      previewModule = arguments[i];
      break;
   }
}

this will be your basic approach. as this is an angular application you can user $injector.get("moduleName")

for example;

var previewModule = $injector.get("'DocumentTypeManager' + document.clientModule");

please see $injector

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.