0

我正在使用 Grails 3 和 AngularJS 配置文件以及Angular Toastr 插件
当我在开发模式下运行应用程序时,一切正常,但是当我捆绑应用程序(没有缩小)时,无法再加载插件中的模板,并且出现以下错误:

Error: [$compile:tpload] Failed to load template: directives/toast/toast.html (HTTP status: 404 Not Found)

我检查了捆绑的代码并找到了以下几行:

angular.module('toastr')
    .constant('toastrConfig', {
      allowHtml: false,
      autoDismiss: false,
      closeButton: false,
      closeHtml: '<button>&times;</button>',
      containerId: 'toast-container',
      extendedTimeOut: 1000,
      iconClasses: {
        error: 'toast-error',
        info: 'toast-info',
        success: 'toast-success',
        warning: 'toast-warning'
      },
      maxOpened: 0,
      messageClass: 'toast-message',
      newestOnTop: true,
      onHidden: null,
      onShown: null,
      onTap: null,
      positionClass: 'toast-top-right',
      preventDuplicates: false,
      preventOpenDuplicates: false,
      progressBar: false,
      tapToDismiss: true,
      target: 'body',
      templates: {
        toast: 'directives/toast/toast.html',
        progressbar: 'directives/progressbar/progressbar.html'
      },
      timeOut: 5000,
      titleClass: 'toast-title',
      toastClass: 'toast'
    });

angular.module("toastr").run(["$templateCache", function($templateCache) {$templateCache.put("directives/progressbar/progressbar.html","<div class=\"toast-progress\"></div>\n");
$templateCache.put("directives/toast/toast.html","<div class=\"{{toastClass}} {{toastType}}\" ng-click=\"tapToast()\">\n  <div ng-switch on=\"allowHtml\">\n    <div ng-switch-default ng-if=\"title\" class=\"{{titleClass}}\" aria-label=\"{{title}}\">{{title}}</div>\n    <div ng-switch-default class=\"{{messageClass}}\" aria-label=\"{{message}}\">{{message}}</div>\n    <div ng-switch-when=\"true\" ng-if=\"title\" class=\"{{titleClass}}\" ng-bind-html=\"title\"></div>\n    <div ng-switch-when=\"true\" class=\"{{messageClass}}\" ng-bind-html=\"message\"></div>\n  </div>\n  <progress-bar ng-if=\"progressBar\"></progress-bar>\n</div>\n");}]);

所以看起来模板在模板缓存中正确初始化。

我尝试在控制器中注入 $templateCache 并调用$templateCache.get("directives/toast/toast.html")它,这将返回正确的模板。

捆绑时模板未正确加载的原因可能是什么,尽管我可以使用它来访问它$templateCache.get(...)
关于 $templateCache 的正确使用,我有什么遗漏吗?

PS:我注意到 angular-bootstrap 模板存在同样的问题

编辑我发现,当我使用绝对 templateUrls 时,一切正常,所以显然,我不完全理解相对 templateUrls 是如何工作的。
捆绑应用程序时,所有 JS 代码都连接到具有不同路径的单个文件中,这似乎会中断通过 $templateCache 的加载。现在,将所有 templateUrls 设为绝对是一个解决方案,但对于使用相对 templateUrl 且不更改其代码的插件,我无法做到这一点。

那么,任何人都可以向我解释这里实际发生了什么以及我如何解决这个问题,而无需触及插件代码?

4

1 回答 1

0

我发现,在为 Angular 生成 Grails 应用程序时,它会自动在 index.gsp 中包含以下行:

<script type="text/javascript">
    window.contextPath = "${request.contextPath}";
</script>

这会设置window.contextPath应用程序何时被捆绑用于生产,这会破坏 Angular $templateCache。

换句话说:设置window.contextPath = ""或来自 $templateCache 的模板解析将失败。

于 2016-09-27T18:52:59.653 回答