2

I have read the documentation for $templateCache but I'm still struggling to understand how to load remote templates into the cache using the put function.

Below is an example:

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'));
}); 

While my code returns the HTML code for tpl1, the path is being returned for tpl2. My question is: How to load a remote template using $templatecache.put().

Thanks for the help.

vegas2033
  • 250
  • 1
  • 4
  • 16

1 Answers1

6

Try to call the remote template and set it up on the 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');
    });
}); 

The main reason for this is that angularjs' templateCache only receives string values, not like on a directive, where you can have a templateUrl, for example.

Here is the doc for this ng-service

Litta Hervi
  • 377
  • 4
  • 12
  • Thanks for the response Litta. Unfortunately, the console only write the 1st template not the second so I assume that it's not being loaded. Also, I had an error in the path for tpl2 it should be '/Templates/Pi/pi-1.html'. – vegas2033 Feb 27 '17 at 21:07
  • Sorry, I had an error in the code above... now should work. Also, you need to be sure to place the correct path for your template. For further information regarding the issue in loading the template, you can debug the 'errorResponse' on the $http function. – Litta Hervi Feb 27 '17 at 22:03
  • Actually there another typo mistake in the get ('pl2.html'). But the code works. Thanks for your help. – vegas2033 Feb 28 '17 at 14:25