Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load $templateCache from file

I've been having trouble loading templates from the $templateCache.

How I put templates in $templateCache :

var app = angular.module('anglober', ['anglober.controllers', 'anglober.services', 'anglober.directives']).run(function ($templateCache, $http) {
    $http.get('anglober/js/invitation/invitationModal.tpl.html', {cache: $templateCache});
    $http.get('anglober/js/modal/ajaxModal.tpl.html', {cache: $templateCache});
    $http.get('anglober/js/ajaxLoader/ajaxLoader.tpl.html', {cache: $templateCache});
    $http.get('anglober/js/modal/modalContent.tpl.html', {cache: $templateCache});
    $http.get('anglober/js/modal/simpleModal.tpl.html', {cache: $templateCache});
    $http.get('anglober/js/mog/topMogs.tpl.html', {cache: $templateCache});

How I load them :

angular.module('anglober.directives').directive('topMogs', ['$templateCache', function ($templateCache) {
return {
    restrict : 'E',
    template: $templateCache.get('topMogs.tpl.html')
    //Tried this too
    // templateUrl: 'topMogs.tpl.html'
};
}]);

In my network browser tab, I can see the templates being loaded at page load.

However I get the following error when calling my directive :

One of template or templateUrl options is required.

What am I doing wrong ?

Thanks

like image 337
Komo Avatar asked Jan 10 '23 05:01

Komo


1 Answers

A small addition to this old thread:

Although there are few ways to achieve your goal, the best approach for me was to add the $templateCache logic into each of my app's directives. This way, I could avoid using any external packages like grunt angular-templates (which is excellent - but kind of an overkill for my app)

angular.module('MyApp')
.directive('MyDirective', ['$templateCache', function($templateCache) {
    return {
        restrict: 'E',
        template: $templateCache.get('MyTemplate'),
        controller: 'MyController',
        controllerAs: 'MyController'
    };
}]).run(function($templateCache, $http) {
    $http.get('templates/MyTemplate.html').then(function(response) {
        $templateCache.put('MyTemplate', response.data);
    })
});

Hope this helps!

like image 57
Shaya Avatar answered Jan 11 '23 18:01

Shaya