在Angular JS中从decorator内部调用工厂服务

Calling factory service from inside decorator in Angular JS

本文关键字:调用 工厂 服务 内部 decorator Angular JS 中从      更新时间:2023-09-26

使用TextAngular插件并尝试自定义工具栏,我试图将自己的服务(LinkService)注入到模块中,但遇到了[$injector:unpr] Unknown provider错误。

module.config(function($provide, LinkService){
    $provide.decorator('taOptions', ['taRegisterTool', '$delegate', function(taRegisterTool, taOptions){
        // $delegate is the taOptions we are decorating
        // register the tool with textAngular
        taRegisterTool('colourRed', {
            iconclass: "fa fa-square red",
            action: function(){
                this.$editor().wrapSelection('forecolor', 'red');
                LinkService.createLink(/*...*/)
            }
        });

        // add the button to the default toolbar definition
        taOptions.toolbar[1].push('colourRed');
        return taOptions;
    }]);
});

如何将我的服务注入此配置?

我们不能将服务注入configuration块。

配置块-在提供程序注册期间执行以及配置阶段。只能注入提供程序和常量转换为配置块。这是为了防止意外实例化在服务完全配置之前。

运行块-在创建并使用注入器后执行以启动应用程序。只有实例和常量可以注入到运行块中。这是为了防止进一步的系统应用程序运行时的配置。

然而,我们可以在提供者中构建类似的逻辑。我不确定LinkService的用法,但作为一个提供者,我可以看到以下内容。。。

module.provider('LinkProvider', function () {
    var link;
    return {
        createLink: function (value) {
            link = value;
        },
        $get: function () {
            return {
                link: 'http://' + link
            }
        }
    }
});
module.config(function (LinkProvider) {
    LinkProvider.createLink('stackoverflow.com');
});

请参阅博客AngularJS中提供商之间的差异,以全面了解提供商