angularjs - Point ng-include to a partial that con

2019-01-29 07:54发布

This is an edit of the original question:

When using the ng-include directive to reuse my header HTML on all pages, there is a slight delay in loading/rendering the top navbar. To alleviate the problem, I'm attempting to point ng-include to a header.html file that contains <script type='text/ng-template' id='header.html>...</script> so that it pre-loads the partial.

But I can't seem to get it to work. I've only had success when sticking the contents of header.html directly in index.html, which defeats the purpose of reusing the header code.

The docs for script only give an example of using an inline template, and the docs for ngInclude don't use script in the example templates.

Can ngInclude load a file that uses angular's script directive?

index.html:

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
  <title>Testing</title>
  <link rel="stylesheet" href="css/bootstrap.css">
  <link rel="stylesheet" href="css/custom.css">
  <script src='lib/angular/angular.js'></script>
  <script src='js/main.js'></script>
</head>
<body>

<div ng-controller="HeaderCtrl">
  <div ng-include src="header.url"></div>
  <!-- script works when it is put directly in index.html:
  <script type="text/ng-template" id="header.html">
  <div class="navbar navbar-fixed-top">
    <div class="navbar-inner">
      <div class="container">
        <ul class="nav">
          <li>
            <a class="brand" href="#">Test</a>
          </li>
          <li><a href="#">One</a></li>
          <li><a href="#">Two</a></li>
          <li><a href="#">Three</a></li>
        </ul>
      </div>
    </div>
  </div>
  </script>
  -->
</div>
</body>
</html>

header.html:

<script type="text/ng-template" id="header.html">
  <div class="navbar navbar-fixed-top">
    <div class="navbar-inner">
      <div class="container">
        <ul class="nav">
          <li>
            <a class="brand" href="#">Test</a>
          </li>
          <li><a href="#">One</a></li>
          <li><a href="#">Two</a></li>
          <li><a href="#">Three</a></li>
        </ul>
      </div>
    </div>
  </div>
</script>

main.js:

"use strict";
// I've also tried this with "use strict"; removed

var myApp = angular.module('myApp', []);

function HeaderCtrl($scope) {
    $scope.header = {name: "header.html", url: "header.html"};
}

2条回答
干净又极端
2楼-- · 2019-01-29 08:35

This works perfectly. Tried it on my server. Double quotes were necessary. What is with the "use strict"; That breaks it on my end.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-29 08:46
<div ng-include src="header.url"></div>

should be

<div ng-include src="'header.url'"></div>

Not sure if this is what rjm226 meant by 'double quotes were necessary'. Both double and single are necessary for ng-include. I've been tripped up by this recently.

查看更多
登录 后发表回答