javascriptangularjsangular-templatecacheangular-config

$templateCache not working in angular-config in Angular.js


I am getting "angular.min.js:6Uncaught Error: [$injector:modulerr]" when trying to use $templateCache in my app.config block, if i remove the $templateCache parameter from app.config then i do not see any errors. Please let me know if i missed out something. Thanks in advance.

var app = angular.module("app", ['ui.router'], function () {
    console.log('Application Initiated Successfully...');
})

.run(function ($templateCache, $http) {
    console.log("app is running");
    $http.get("Views/home2.html", { cache: true }).success(function (html) {        
        $templateCache.put("Test.html", html);
        console.log($templateCache.get("Test.html"));
    });
    console.log($templateCache.info());    
});
   

app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$templateCache', function ($stateProvider, $urlRouterProvider, $locationProvider, $templateCache) {
    $urlRouterProvider.otherwise("/");

    $stateProvider
        .state("/", {
            url: "/",
            templateUrl: "Views/home.html"            
        });
}]);

app.controller("indexController", ["$rootScope", "$scope", function ($rootScope, $scope) {
    console.log('indexController');
    $scope.message = "Hi lets get started...";    
} ]);


Solution

  • You cannot access service at time of angular config. You can access your service inside your app.run block. $templateCache is a service that you are trying to use in your config block.

    However, You can access it inside your resolve block of a state.

    $stateProvider
            .state("/", {
                url: "/",
                templateUrl: "Views/home.html",
                resolve: {
                  data: function ($templateCache,dbService) {
                  return dbService.getData();
                }
            });
    

    You can only access providers at time of config block of an angular.

    Find below link to understand more about config block of angular. https://docs.angularjs.org/guide/module

    Below is a description from its official site.