AngularJS 控制器工作但不加载 html 页面

AngularJS controller works but does not load html page

我的控制器出现了一些意想不到的问题,这是在构建第一个 angular 项目期间发生的,就像这里:https://www.youtube.com/watch?v=8-ZQHv70BCw&t=2119s 问题是我的 link 主页没有加载,它没有任何效果,即使控制台显示消息并且没有 return 任何错误。我在 plunkr 上测试了这个。

index.html:

<!DOCTYPE HTML>
<html lang="en" ng-app="computer">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Computer Solutions</title>

    <!-- Bootstrap core CSS -->
    <link href="bootstrap.min.css" rel="stylesheet">
    <!-- Custom styles for this template -->
    <link href="style.css" rel="stylesheet">
  </head>

  <body>

    <div class="container">

      <!-- The justified navigation menu is meant for single line per list item.
           Multiple lines will require custom code not provided by Bootstrap. -->
      <div class="masthead">
        <h3 class="text-muted">Computer solutions</h3>
        <nav>
          <ul class="nav nav-justified">
            <li><a href="#/main">Home</a></li>
            <li><a href="about.html">About</a></li>
            <li><a href="services.html">Services</a></li>
            <li><a href="contact.html">Contact</a></li>
          </ul>
        </nav>
      </div>

<div ng-controller='MainCtrl'>
  <div ng-view></div>
</div>

      <!-- Site footer -->
      <footer class="footer">
        <p>&copy; 2016 Company, Inc.</p>
      </footer>

    </div> <!-- /container -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
<script src="https://code.angularjs.org/1.6.1/angular.js"></script>
<script src="https://code.angularjs.org/1.6.1/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.js"></script>
<script src="script.js"></script>
  </body>
</html>

script.js

var app = angular.module("computer",['ngRoute'])


.config(['$routeProvider', function($routeProvider){
  $routeProvider.
  when('/main', {
    templateUrl: 'main.html',
    controller: 'MainCtrl'
 });

}])
.controller('MainCtrl', [function(){
  console.log('this is mainctrl');
}]);

和main.html

this is main.

提前致谢,迈克尔

我猜你在 html 和 routeProvider 中也提到了 Controller(MainCtrl)。尝试删除其中一个地方。 检查

已将您的导入更改为 1.4.8 版本。您包含的版本似乎在没有 otherwise$route 定义上有问题:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>

我还添加了其他状态,应该都可以。

app.config(['$routeProvider', function($routeProvider) {
  $routeProvider.
  when('/main', {
    templateUrl: 'main.html',
    controller: 'MainCtrl'
  }).
  when('/about', {
    templateUrl: 'about.html',
  }).
  when('/services', {
    templateUrl: 'services.html',
  }).
  when('/contact', {
    templateUrl: 'contact.html',
  })
}])

查看工作版本:https://plnkr.co/edit/ebB3GAnoDSunsHK4bpme