【问题标题】:templateUrl function is not using explicit annotation and cannot be invoked in strict modetemplateUrl 函数未使用显式注释,无法在严格模式下调用
【发布时间】:2016-07-14 20:51:58
【问题描述】:

我正在尝试创建一个自定义角度组件,该组件可以根据 templateUrl 函数动态加载模板。我目前得到一个 templateUrl 没有使用显式注释并且不能在严格模式下调用的错误。通常我知道当注入的服务没有得到正确注释时会出现这个错误(https://docs.angularjs.org/error/$injector/strictdi)。但是,我错过了这如何适用于templateUrl

我正在使用 Angular 1.5。

确切的错误信息是 - angular.js:13550 Error: [$injector:strictdi] templateUrl is not using explicit annotation and cannot be invoked in strict mode

组件代码sn-p:

angular.module('hive.triGrid')
.controller('TriGridCellController', ['$element', '$attrs', function     ($element, $attrs) {
    var $ctrl = this;
}]) 
.component('triGridCell', {
controller: 'TriGridCellController',
templateUrl: function($element, $attrs)
{
    var type = $attrs.cellType;
    if(type.toUpperCase() == "ICON")
    {
        return "components/grid/cellTemplates/iconCell.tpl.html";
    }
    else if(type.toUpperCase() == "CUSTOM")
    {
        return $attrs.cellTemplateUrl;
    }
    else
    {
        return "components/grid/cellTemplates/textCell.tpl.html"; 
    }
},
//template:"<ng-include src='$ctrl.getTemplateUrl(z)'/>",
bindings: {
    cellData:'<',
    cellType: '<', //See triGridRow and triGrid for config JSON format.
    }
});

编辑: 应用答案后的代码:

templateUrl: ['$element', '$attrs', function($element, $attrs)
{
    var type = $attrs.cellType;
    if(type.toUpperCase() == "ICON")
    {
        return "components/grid/cellTemplates/iconCell.tpl.html";
    }
    else if(type.toUpperCase() == "CUSTOM")
    {
        return $attrs.cellTemplateUrl;
    }
    else
    {
        return "components/grid/cellTemplates/textCell.tpl.html"; 
    }
}],

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    正如 in this answer 所说,$element$attrs 被注入到 templateUrl 函数中,而不仅仅是作为参数传递。这是 element 参数名称(在 linkcompile 函数中)和 $element Angular 文档强调的启用 DI 的函数中的本地依赖之间的区别。

    templateUrl 函数在组件中是invoked by injector,因此任何其他服务也可以在那里注入,并且应该正确注释。

    【讨论】:

    • 出于某种原因,我不认为将其应用于组件设置功能。这对我有用。
    • 这是指令工厂函数的替代品,因此可以将服务注入到组件中需要它们的每个地方。
    • 我仍然面临的一个问题是 $attrs.cellType 从我的模板返回原始文本,而不是应该传入的实际控制器值。我正在尝试解析模板基于配置,而不是预先确定的文本。在这种情况下,我是否需要开始涉足编译和链接以及使用原始指令?
    • 没错。如链接答案中所述,templateUrl 不能用于获取插值属性,因为该函数在指令 compile 之前执行,并且在第一个摘要之前很久。组件应该是简单的自包含小部件,并且您尝试做的事情类似于 ng-include 指令,它足够复杂和复杂。如果可以将 $attrs.cellType 设为静态并使用其原始值,这将为您省去很多麻烦。
    • 不可能使用静态值,但我可以把它变成指令而不是组件。
    猜你喜欢
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    相关资源
    最近更新 更多