捆绑后相对templateUrls的Angular $ templateCache 404错误

时间:2016-09-24 12:16:52

标签: javascript angularjs grails bundling-and-minification angular-templatecache

我使用Grails 3和AngularJS配置文件以及Angular Toastr plugin 当我在开发模式下运行应用程序时,一切都运行良好,但是当我捆绑应用程序(没有缩小)时,插件中的模板不再被加载,我收到以下错误:

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的插件做到这一点,而不更改他们的代码。

那么,任何人都可以向我解释这里实际发生了什么,以及如何在不触及插件代码的情况下解决这个问题?

1 个答案:

答案 0 :(得分:0)

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

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

当应用程序捆绑生产时会设置window.contextPath,从而打破Angular $ templateCache。

换句话说:设置window.contextPath = ""或$ templateCache的模板分辨率将失败。