gpt4 book ai didi

javascript - 从服务 AngularJS + TypeScript 调用指令

转载 作者:行者123 更新时间:2023-12-02 16:36:59 24 4
gpt4 key购买 nike

我正在尝试从服务调用指令。我已经实现了一切,但我的服务范围却空了。通常我的函数从 Controller 调用指令。但现在需要跨多个 Controller 使用这些功能,因此我想将它们放入服务中。问题是即使在将指令依赖注入(inject)到服务中之后,我的服务也无法看到指令中的功能。

    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
}
});
}

那么我该怎么做才能让服务查看该指令并调用其函数呢?

最佳答案

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

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

关于javascript - 从服务 AngularJS + TypeScript 调用指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27850653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com