从服务angularjs + typescript调用指令

时间:2015-01-08 22:25:38

标签: javascript angularjs angularjs-directive typescript angularjs-service

我试图从服务中调用指令。我实现了一切,但我的服务范围空洞。 Normaly我的函数是从控制器调用指令。但是现在需要跨多个控制器使用这些功能,所以我想把它们放在一个服务中。问题是我的服务即使在将指令依赖注入服务之后也无法看到指令中的函数。

    export interface MyServiceScope extends IScope, directives.MyPanelScope, directives.MyPanelMenuScope {
            // a bunch of properties that are not visible in the service scope, only the controller
        }

// constructor here, controller does not initialize directives here just in interface and it works fine.

    public serviceFunc() {
        this.scope.panel.directiveFunc({ // directiveFunc undefined in service, but not in controller
            template: "some/html/template",
            data: {
                item: data
            }
        });
    }

那么如何让服务看到指令并调用它的函数呢?

1 个答案:

答案 0 :(得分:2)

您无法将指令注入服务n Angular。实际上你不能在任何地方注入指令。 指令应该是一组与特定DOM元素严格相关的函数,使用它们在应用程序的不同部分之间共享代码通常是不好的做法。这个目的可以通过服务来实现。

如果您发现自己处于服务需要从指令调用某个函数的情况,我建议您检查您的代码结构。我不知道你的案例的具体细节,但你可以将你的指令中的“共享”逻辑带入服务,将该服务注入指令并从那里调用它。通过这种方式,指令调用的逻辑也可以注入应用程序的其他部分。

相关问题