angularjs将接口绑定到多个实现

时间:2015-05-27 06:24:51

标签: javascript angularjs dependency-injection ninject

我想将一个接口的不同实现注入到angularjs服务中,但是我似乎找不到这样做的方法。有没有办法配置angularjs注入器将接口绑定到实现?类似于Ninject或Guice等其他DI框架的使用。 例如

var myInterface = function() {
    return {
        func: {}
    };
}

var impl1 = function() {
    return {
        func: function() {
            console.log("implementation 1");  
        }
    };
}

var impl2 = function() {
    return {
        func: function() {
            console.log("implementation 2");  
        }
    };
}

var app = angular.module("app", ["myInterface"]);

app.service("myService1", function(myInterface) {
    myInterface.func();  //should output "implementation 1"
});

app.service("myService2", function(myInterface) {
    myInterface.func();  //should output "implementation 2"
});

//I would like to do something as follows, similar to how one would use Ninject for eg
//Assume myInterface, impl1, impl2 are all angular services
bind("myInterface").to("impl1").wheninjectedinto("myService1");
bind("myInterface").to("impl2").wheninjectedinto("myService2");

0 个答案:

没有答案