jonfaulkenberry
jonfaulkenberry

Reputation: 96

Angular.js templates not rendering until leaving and returning to route

I am trying to preload my templates using $templateCache. When a view in my app initially loads, however, it does not render in the browser. Only after I return to the route a second time does the template render. What could be causing this?

I am preloading my templates into a module like so:

angular.module("templateCache", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("views/view2/view2.html", "<script type=\"text/ng-template\" id=\"views/view2/view2.html\">\n<p>This is the partial for view 2.</p>\n$templateCache: {{ $templateCache }}\n</script>");
  $templateCache.put("views/view1/view1.html", "<script type=\"text/ng-template\" id=\"views/view1/view1.html\">\n<p>This is the partial for view 1.</p>\n$templateCache: {{ $templateCache }}\n</script>");
}]);

I am then requiring this module as a dependency in my app module and using these templates in my app controllers using templateUrl, like so:

angular.module("myApp", ["ngRoute", "templateCache", "myApp.view1", "myApp.view2"]).config(["$routeProvider", function(e) {
  e.otherwise({
      redirectTo: "/view1"
  })
}]), angular.module("myApp.view1", ["ngRoute"]).config(["$routeProvider", function(e) {
  e.when("/view1", {
      templateUrl: "views/view1/view1.html",
      controller: "View1Ctrl"
  })
}]).controller("View1Ctrl", ["$templateCache", function(e) {
   console.log(e.get("views/view1/view1.html"))
}]), angular.module("myApp.view2", ["ngRoute"]).config(["$routeProvider", function(e) {
  e.when("/view2", {
      templateUrl: "views/view2/view2.html",
      controller: "View2Ctrl"
  })
}]).controller("View2Ctrl", [function() {}]);

Please see this Plunker demonstrating my issue: http://plnkr.co/edit/4rcR8aZQ8fiIRrzsLPiR

Upvotes: 0

Views: 139

Answers (1)

Boris Zagoruiko
Boris Zagoruiko

Reputation: 13164

You should not paste those <script> tags to cached view.

$templateCache.put("views/view1/view1.html", "<p>This is the partial for view 1.</p>");
$templateCache.put("views/view2/view2.html", "<p>This is the partial for view 2.</p>");

I test it with your plunker demo and erverything seems to work fine.

Upvotes: 1

Related Questions