9

我有一个非常简单的 AngularJS 模板,我试图让路由工作,但是当我加载页面时,我只是从我的index.html.

我的应用程序位于子目录中/angular-route/,并且我知道部分存在,我可以访问/angular-route/partials/interest.html并且页面呈现正常。

我在这里错过了一些非常基本的东西吗?

<html>
<head ng-app="myApp">
    <title>AngularJS Routing</title>
    <base href="/angular-route/" />
</head>
<body>

<h1>AngularJS Routing</h1>

<div ng-view></div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>

<script>
    'use strict';

    var myApp = angular.module('myApp', []).
      config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/interest', {
                templateUrl: 'partials/interest.html',   
                controller: 'InterestCtrl'
            }).
            when('/catalogue', {
                templateUrl: 'partials/catalogue.html', 
                controller: 'CatalogueCtrl'
            }).
            otherwise({redirectTo: '/interest'});
    }]);

    myApp.controller('InterestCtrl', function($scope, $routeParams) {
        console.log('InterestCtrl');
    });
    myApp.controller('CatalogueCtrl', function($scope, $routeParams) {
        console.log('CatalogueCtrl');
    });
</script>

4

2 回答 2

26

除了您需要的基本标记之外,您还将ng-app 指令放置在错误的元素 ( head) 上。在您的代码中,应用程序仅在标头内初始化。Angular 会忽略 HTML 的其余部分。

工作柱塞

<html ng-app="myApp">
<head>
  <title>AngularJS Routing</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <script type="text/ng-template" id="partials/interest.html">
    <h2>Inereset</h2> 
  </script>
  <script type="text/ng-template" id="partials/catalogue.html">
    <h2>Catalogue</h2> 
  </script>
</head>
<body>

  <h1>AngularJS Routing</h1>

  <ul>
    <li><a href="#/interest">Interest</a></li>
    <li><a href="#/catalogue">Catalogue</a></li>
  </ul>

  <div ng-view></div>

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>

  <script>
      'use strict';

      var myApp = angular.module('myApp', []).
        config(['$routeProvider', function($routeProvider) {
          $routeProvider.
            when('/interest', {
              templateUrl: 'partials/interest.html',   
              controller: 'InterestCtrl'
            }).
            when('/catalogue', {
              templateUrl: 'partials/catalogue.html', 
              controller: 'CatalogueCtrl'
            }).
            otherwise({redirectTo: '/interest'});
      }]);

      myApp.controller('InterestCtrl', function($scope, $routeParams) {
        console.log('InterestCtrl');
      });
      myApp.controller('CatalogueCtrl', function($scope, $routeParams) {
        console.log('CatalogueCtrl');
      });
  </script>
</body>
</html
于 2013-06-29T07:32:05.277 回答
4

以下配置对我有用!

假设我们想使用http://localhost:8000/app/

在此处输入图像描述

然后让您的基本标签突出显示以下内容

在此处输入图像描述

于 2016-07-12T15:32:58.033 回答