user3615920 user3615920 - 2 months ago 6
AngularJS Question

How to have a two separate implementation based on some condition in angularjs

My situation is as below

function abc(){
if(someCondition){

// Implemention 1

} else {

// Implemention 2

}


}


This kind of situation is in the whole application, but I want to get my code to be clean.
I want to have something like in c#, where by dependency injection I can select between two classes on runtime and switch between classes with Class1 with"Implementaion 1" and Class2 with "Implemention 2". I am using angularjs 1.x

Example :
I have approx 20 controllers and services in "Implementation 1" and same 20 controller and services in "Implementation 2". Can you please help me how can can I design my application so that if my application is in "Mode 1" then it should use "Implementation 1" and in runtime if it switched to "Mode 2" than it should use "Implementation 2"


Please give some sugestions.

Answer

You can certainly do it by using $injector, here is the code:

angular.module('myApp').controller('myCtrl', 
    ['$injector', '$scope',
    function($injector, $scope) {
        var service;
        if (something) {
            service = $injector.get('myService1');
        }else{
            service = $injector.get('myService2');
        }
    });