AngularJS 路由功能不起作用

AngularJS Routing Function is not working

本文关键字:不起作用 功能 路由 AngularJS      更新时间:2023-09-26

我的角度路由函数不起作用 - 有一个页面加载,但没有"home.html"文件。这是我的代码:

索引.html

<html  ng-app="App" class="no-js" lang="en" >
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
    <script src="app.js"></script>    
  </head>
  <body ng-cloak> 
  <div ng-controller="main">
      <div ng-view></div>
    </div>
  </body>
</html>

应用.js

(function () {
'use strict';
angular
    .module('App', ['ngRoute']) 
    .controller('$routeProvider', router)
    .controller('main', main);
function router($routeProvider) {
    $routeProvider.
          when('/', {
            templateUrl: '_pages/home.html',
            controller: 'main'
          });
};
function main ($scope) {
console.log("done");
}

Angular $providers仅在配置状态下工作。例如:

angular
.module('App', ['ngRoute']) 
.config(['$routeProvider', router]);
function router($routeProvider) {
    $routeProvider.
      when('/', {
        templateUrl: '_pages/home.html',
        controller: 'main'
      });
};

路由配置是在配置而不是控制器中完成的。更改您的代码,如下所示:

(function () {
  'use strict';
   angular
    .module('App', ['ngRoute']) 
    .config(router)
    .controller('main', main);
  function router($routeProvider) {
    $routeProvider.
      when('/', {
        templateUrl: '_pages/home.html',
        controller: 'main'
      });
  };
  function main ($scope) {
    console.log("done");
  }
});