angularjsangularjs-templates

AngularJS - $templateCache is not defined


I am trying to load a template file in an AngularStrap popover, however I am having trouble using $templateCache. I seem to be a step further back than the other SO questions, hence this seemingly double one.

Following the API docs I added a <script type="text/ng-template" id="popoverTemplate.html"></script> right before the closing </body> tag. When I use <div ng-include="'popoverTemplate.html'"></div> on my page, I get nothing. If I try using console.log($templateCache.get("popoverTemplate.html")) I get "$templateCache is not defined", which leads me to assume I am missing a crucial step. However, I can't find how to do it in the docs or other SO questions.

EDIT: Injecting the service was the missing link. However, when I inject the service, the controller's other function no longer works, but if you inject al the function's parameters the working code becomes:

(function() {
    "use strict";
    angular.module("app").controller("managerController", ["$scope", "imageHierarchyRepository", "$templateCache", function ($scope, imageHierarchyRepository, $templateCache) {
        imageHierarchyRepository.query(function(data) {
            $scope.hierarchies = data;
        });

        var template = $templateCache.get("popoverTemplate.html");
        console.log(template);
    }]);
})();

Solution

  • To use the template script tag . You have to insert it inside the angular application. That is inside the element with the ng-app attribute or the element used to bootstrap the app if you don't use the ng-app tag.

    <body ng-app="myapp">
    
      <div ng-template="'myTemplate.html'"></div>
    
      <script type="text/ng-template" id="myTemplate.html">
        // whate ever
      </script>
    </body> 
    

    If you want to retrieve the template on a component of the application then you need to inject the service where you want to consume it:

    controller('FooCtrl', ['$templateCache', function ($templateCache) {
      var template = $templateCache.get('myTemplate.html');
    }]);
    

    Or

    controller('FooCtlr', FooCtrl);
    
    FooCtrl ($templateCache) {};
    
    FooCtrl.$inject = ['$templateCache'];
    

    EDIT

    Do not register two controllers with the same name because then you override the first one with the last one.

    (function() {
        "use strict";
        angular.module("app").controller("managerController",["$scope", "imageHierarchyRepository", "$templateCache", function ($scope, imageHierarchyRepository, $templateCache) {
            var template = $templateCache.get("popoverTemplate.html");
            console.log(template);
            imageHierarchyRepository.query(function(data) {
                $scope.hierarchies = data;
            });
        }]);
    
    
    })();