Angular.js 组件动态模板URL

Angular.js components dynamic templateURL

我正在尝试使用 angular 组件创建动态 templateUrls。但是我得到这个错误:

Error: [$injector:unpr] Unknown provider: eProvider <- e

angular
    .module('myApp')
    .component('fieldComponent', {
        templateUrl: function ($element, $attrs) {
           return $attrs.templateUrl || 'some/path/default.html'
        },
        controller:fieldComponentController,
        controllerAs:'vm',
        $routeConfig: [
            {path: '/dashboard', component: 'dashboardApp', name: 'Dashboard', useAsDefault: true}
        ]
    });

随着文件越来越小,它的抛出错误如上。那么我应该在哪里以及如何注入这个依赖项呢?

我猜你在 fieldComponentController 中的 DI 被缩小破坏了。当代码被缩小时,您的依赖项的名称将更改为 'e' 之类的名称,Angular 不知道如何处理。

解决这个问题的一种方法是利用 ng-annotate (https://github.com/olov/ng-annotate) 以最小化安全的方式重写这些变量名。

如果您使用像 Webpack 这样的构建工具来进行打包和缩小,您只需将 ngAnnotatePlugin 添加到您的配置中,并在控制器定义的顶部包含字符串 'ngInject'

angular.module("MyMod").controller("MyCtrl", function($scope, $timeout)        
{
"ngInject";
...
});

ES2015 版本:

export class MyCtrl {
    constructor($scope, $timeout){
        'ngInject';
    }
}

按照@Matt Richards 的建议,我可以通过在顶部添加 /@ngInject/ 来做到这一点。

/*@ngInject*/
angular
    .module('myApp')
    .component('fieldComponent', {
        templateUrl: function ($element, $attrs) {
           return $attrs.templateUrl || 'some/path/default.html'
        },
        controller:fieldComponentController,
        controllerAs:'vm',
        $routeConfig: [
            {path: '/dashboard', component: 'dashboardApp', name: 'Dashboard', useAsDefault: true}
        ]
    });

但是,最后我 ng-include 宁愿采用动态模板方法,也节省了我覆盖单元测试用例的时间。