【问题标题】:How to load a remote template using $templatecache.put()如何使用 $templatecache.put() 加载远程模板
【发布时间】:2017-07-18 15:18:26
【问题描述】:

我已经阅读了 $templateCache 的文档,但我仍然难以理解如何使用 put 函数将远程模板加载到缓存中。

下面是一个例子:

onBoardingApp.run(function ($templateCache, $http) {
  $templateCache.put('tpl1.html', '<p>Hello World</p>');
  $templateCache.put('tpl2.html', '~/Templates/Pi/pi-1.html');
  alert($templateCache.get('tpl1.html'));
  alert($templateCache.get('tpl2.html'));
}); 

虽然我的代码返回 tpl1 的 HTML 代码,但正在返回 tpl2 的路径。我的问题是:如何使用 $templatecache.put() 加载远程模板。

感谢您的帮助。

【问题讨论】:

    标签: angularjs caching angular-templatecache


    【解决方案1】:

    尝试调用远程模板并在templateCache上设置:

    onBoardingApp.run(function ($templateCache, $http) {
        $templateCache.put('tpl1.html', '<p>Hello World</p>');
        console.log($templateCache.get('tpl1.html'));
        $http.get('/Templates/Pi/pi-1.html').then(function (response) {
            $templateCache.put('tpl2.html', response.data);
            console.log($templateCache.get('pl2.html'));
        }, function (errorResponse) {
            console.log('Cannot load the file template');
        });
    }); 
    

    主要原因是 angularjs 的 templateCache 只接收字符串值,不像在指令中,你可以有一个 templateUrl,例如。

    Here 是这个 ng-service 的文档

    【讨论】:

    • 感谢丽塔的回复。不幸的是,控制台只写第一个模板而不是第二个,所以我假设它没有被加载。另外,我在 tpl2 的路径中有一个错误,它应该是 '/Templates/Pi/pi-1.html'。
    • 对不起,我在上面的代码中有一个错误......现在应该可以工作了。此外,您需要确保为模板放置正确的路径。有关加载模板问题的更多信息,您可以在 $http 函数上调试“errorResponse”。
    • 实际上在 get ('pl2.html') 中还有一个拼写错误。但是代码有效。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 2012-01-30
    • 2021-03-29
    相关资源
    最近更新 更多