ng模板作为空字符串添加到$templateCache

ng-template added to $templateCache as empty string

本文关键字:添加 templateCache 字符串 ng      更新时间:2023-09-26

我有以下html

<div ng-app="theapp" id="ng-app">
    <!-- templates -->
    <script type="text/ng-template" src="https://app.com/templates/about.html" id="templates/about.html"></script>
    <ion-nav-view></ion-nav-view>
</div>

我希望'templates/about.html'$templateCache。。。它是。。。(不是undefined)。。。但是该值是一个空字符串。我正在我的角度模块控制器中的Chrome调试器中检查这一点。

我做错了什么?

1)。不能使用脚本type="text/ng-template"指向外部URL模板文件。当Angular看到这种具有自定义模板类型的脚本标记时,它将使用它们的内部文本内容放入模板缓存中。Angular不会下载任何内容。

为了参考,我可以把scriptDirective:的编译函数放在这里

compile: function(element, attr) {
  if (attr.type == 'text/ng-template') {
    var templateUrl = attr.id,
        // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
        text = element[0].text;
    $templateCache.put(templateUrl, text);
  }
}

正如您所看到的,在您的案例中,最终得到空字符串模板也就不足为奇了:您的src属性从未使用过,脚本文本确实是空的。

2)。虽然我认为这不是一个很好的主意,但可以再创建一个script指令(因为你可以有很多同名指令),这将尊重src并为你下载模板:

.directive('script', ['$templateCache', '$http',
    function($templateCache, $http) {
        return {
            restrict: 'E',
            terminal: true,
            compile: function(element, attr) {
                if (attr.type == 'text/ng-template' && attr.src && !attr.id) {
                    $http.get(attr.src, { cache: $templateCache });
                }
            }
        };
    }
]);

演示:http://plnkr.co/edit/TChPjDr9iAq4Zi55N0rq?p=preview