2017-02-27 65 views
0

我已閱讀$ 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()加載遠程模板。

感謝您的幫助。

回答

2

嘗試調用遠程模板,並設置它的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服務的文檔

+0

感謝您的回覆Litta。不幸的是,控制檯只寫第一個模板,而不是第二個,所以我假設它沒有被加載。另外,我在tpl2的路徑中遇到錯誤,應該是'/Templates/Pi/pi-1.html'。 – vegas2033

+0

對不起,我在上面的代碼中有錯誤...現在應該工作。另外,您需要確保爲您的模板放置正確的路徑。有關加載模板時問題的更多信息,您可以在$ http函數上調試'errorResponse'。 –

+0

其實在get('pl2.html')中有另一個錯字錯誤。但代碼起作用。謝謝你的幫助。 – vegas2033