【问题标题】:check if "text/ng-template" exists检查“text/ng-template”是否存在
【发布时间】:2015-07-07 02:03:25
【问题描述】:

我正在编写一个小工具,我需要检查是否定义了某个 ng-template。 我所有的模板都是这样定义的:

<script type="text/ng-template" id="example.html">...</script>

所以通过 $http 检查文件是否存在对我来说不起作用。 我如何检查是否定义了所述模板? 到目前为止我看到的唯一选择是检查 DOM:

if(angular.element.find('script#example.html').length > 0) { ...

...但我真的很喜欢不需要检查 DOM 的更好的解决方案。

【问题讨论】:

    标签: angularjs angularjs-ng-template


    【解决方案1】:

    Script directive 如果是模板,则将模板内容放入$templateCache(来源ref.)。这意味着您应该能够通过检查模板是否存在于缓存中来检查模板是否存在:

    if ($templateCache.get('example.html')) {
        // template is on the page
    }
    

    【讨论】:

    • 如果我使用$templateCache.get('example.html'),它将尝试从当前网址加载“example.html”,然后抛出错误。它不会返回 false 或 null。
    • 不,它会检查模板是否被缓存,如果在缓存中则返回缓存的 HTML。否则它将返回undefined$templateCache.get 不会加载任何内容 (source)。
    猜你喜欢
    • 2016-12-06
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 2013-07-29
    相关资源
    最近更新 更多