Angular 组件相对 templateUrl

Angular component relative templateUrl

我正在开发一个模块化 angular 应用程序,我在 angular-module-1 模块中定义了文件夹路径(常量:BASE_PATH:"path/to/folder")。我想在位于我的应用程序的另一个模块 (angular-module-2) 中的 angular 组件中重新使用此常量。我想在我的项目中多次使用这个常量。

module.component("relationshipSearch", {
templateUrl: BASE_PATH +'/link/to/other/folder',

是最好的方法,将这个常量定义为在所有解决方案项目中可见的全局变量 这是我的项目结构:

project
|-- angular-module-1
|   |-- angular-module-1.js
|   |-- angular-module-1.html
|-- angular-module-2
|   |-- angular-module-2.js
|   |-- angular-module-2.html

也许不同的方法可能会有所帮助。为什么不直接查看同一目录中的文件,而不是设置路径。

您可以使用 require(),例如:

template: require('./template-in-same-dir.html')

注意 template 而不是 templateUrl

我会说创建一个名为 angular-common 的通用模块,您可以在其中放置 common 诸如通用 servicefactorydirective 之类的东西, constants, 等等

然后在angular-common(这将是完全独立和可插入的)模块中添加常量。如下所示

//assuming `angular-common` is already defined
angular.module('angular-common').constant('commmonSetting', {
  'BASE_PATH': '/link/to/other/folder'
})

接下来,将这个公共模块注入app(这是主要模块,将在ng-app/bootstrap中使用),如下所示

angular.module('app', ['angular-common', 'ngRoute', ...other dependencies..])

当您想使用 BASE_PATH 时,只需在 controller/component 中任意位置注入 commmonSetting 依赖项即可。

app.component('myComponent', {
  templateUrl: function(commmonSetting){
    return commmonSetting.BASE_PATH +'/link/to/other/folder';
  },
  ....
})

抱歉,在旧线程上发布了一个已接受的答案,但我想说已接受的答案不是缩小安全的。写这个的缩小安全方法是:

app.component('myComponent', {
  templateUrl: function($injector){
    var commmonSetting = $injector.get('namespace.CommmonSetting');
    return commmonSetting.BASE_PATH +'/link/to/other/folder';
  },
  ....
});