从服务 AngularJS + TypeScript 调用指令

call a directive from a service angularjs + typescript

本文关键字:调用 指令 TypeScript 服务 AngularJS      更新时间:2023-09-26

我正在尝试从服务调用指令。我已经实现了所有内容,但我的服务范围是空的。通常,我的函数正在从控制器调用指令。但是现在跨多个控制器需要这些功能,因此我想将它们放在服务中。问题是我的服务即使在将指令的依赖项注入到服务中后也看不到指令中的函数。

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

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

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

如果您发现自己处于服务需要从指令调用某些函数的情况,我建议您查看代码结构。我不知道您的具体情况,但是您可以将指令中的"共享"逻辑转移到服务中,将该服务注入指令并从那里调用它。这样,指令调用的逻辑也可以注入到应用程序的其他部分。