角度.js模板在离开并返回路由之前不会渲染

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

本文关键字:路由 返回 js 离开 角度      更新时间:2023-09-26

我正在尝试使用$templateCache预加载我的模板。但是,当我的应用中的视图最初加载时,它不会在浏览器中呈现。只有在我第二次返回路线后,模板才会呈现。可能是什么原因造成的?

我正在将我的模板预加载到一个模块中,如下所示:

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>");
}]);

然后,我需要将此模块作为我的应用程序模块中的依赖项,并使用 templateURL 在我的应用程序控制器中使用这些模板,如下所示:

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() {}]);

请看这个 Plunker 演示我的问题:http://plnkr.co/edit/4rcR8aZQ8fiIRrzsLPiR

不应将这些<script>标记粘贴到缓存视图中。

$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>");

我用你的 plunker 演示对其进行了测试,似乎工作正常。