javascript - 如何根据AngularJS中的某些条件进行两个单独的实现

标签 javascript angularjs

我的情况如下

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"

请给一些建议。

最佳答案

你当然可以使用$injector来做到这一点,这是代码:

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

关于javascript - 如何根据AngularJS中的某些条件进行两个单独的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39708548/

相关文章:

javascript - 从顶部悬停动画

javascript - 如果它是一个多页面应用程序,在 AngularJS 应用程序中创建一个全局 ng-app 范围是否有意义?

javascript - AngularJS 中的表单始终无效

javascript - 与内容脚本的所有实例对话

angularjs - IE10 将状态代码 401/403 解释为网络错误

javascript - jqscroll/jqscrollTo 根本不工作

javascript - 在 reactjs 中更新嵌套状态

javascript - 网格中的最后一列需要自定义标题

javascript - 为什么 angular2 表单不能正确地与 html <form> 元素一起使用?

javascript - 按下按钮时全局变量没有改变(范围问题)