問題描述

我第一次使用 AngularJS,並且努力使用 ng-include 作為我的頁眉和頁腳。

這是我的樹:

myApp
assets
   - CSS
   - js
        - controllers
        - vendor
             - angular.js
             - route.js
             ......
             ......
             ......
        main.js
pages
   - partials
        - structure
              header.html
              navigation.html
              footer.html
   index.html
   home.html

index.html 的:

<!DOCTYPE html>
<html ng-app="app">
<head>
    <title>AngularJS Test</title>

    <script src="/assets/js/vendor/angular.js"></script>
    <script src="/assets/js/vendor/route.js"></script>
    <script src="/assets/js/vendor/resource.js"></script>
    <script src="/assets/js/main.js"></script>

</head>
    <body>

        <div ng-include src="partials/structure/header.url"></div>
        <div ng-include src="partials/structure/navigation.url"></div>

        <div id="view" ng-view></div>

        <div ng-include src="partials/structure/footer.url"></div>
    </body>
</html>

main.js

var app = angular.module("app", ["ngResource", "ngRoute"]);


app.config(function($routeProvider) {

$routeProvider.when("/login", {
    templateUrl: "login.html",
    controller: "LoginController"
});

$routeProvider.when("/home", {
    templateUrl: "home.html",
    controller: "HomeController"
});

$routeProvider.otherwise({ redirectTo: '/home'});

});

app.controller("HomeController", function($scope) {
    $scope.title = "Home";
});

home.html 的

<div>
<p>Welcome to the {{ title }} Page</p>
</div>

當我在 home.html 頁面上,我的標題,導航和頁腳沒有出現。

最佳解決方案

你正在做一個 header.url 而不是 header.html 。看起來你想在 src 屬性中使用文字,所以你應該用引號括起來,如 @DiscGolfer 的註釋所述。

更改

 <div ng-include src="partials/structure/header.url"></div>
 <div ng-include src="partials/structure/navigation.url"></div>

 <div id="view" ng-view></div>

 <div ng-include src="partials/structure/footer.url"></div>

 <div ng-include src="'partials/structure/header.html'"></div>
 <div ng-include src="'partials/structure/navigation.html'"></div>

 <div id="view" ng-view></div>

 <div ng-include src="'partials/structure/footer.html'"></div>

如果這不工作,請檢查瀏覽器控制枱是否有 404

次佳解決方案

我有一個類似的問題,一個簡單的 ng-include 不渲染:

<div ng-include="views/footer.html"></div>

我用單引號包裝文件路徑,現在渲染:

<div ng-include="'views/footer.html'"></div>

第三種解決方案

我有一個類似的問題,讓我在這裏。

ng-include 沒有填充我的部分內容,但沒有控制枱錯誤,也沒有 404 的。

然後我意識到我做了什麼

修復我:確保您在 ng-include 之外有 ng-app!很明顯作為角色的價格。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇