Angular 1.5 路由示例

Angular 1.5 routing example

我正在尝试使用 $route 查找 angular 1.5 路由示例。如果我使用比用于创建代码示例的 angular 更高的版本,我看过的 JSFiddle 示例就会中断。我找不到任何高于 1.2 的东西。理想情况下,我需要一个 AngularJS 1.5.

的工作示例

我已经试过了this例子:

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

app.config( function ( $routeProvider ) {
  $routeProvider
  .when( '/this', { templateUrl: 'this.html' } )
  .when( '/that', { templateUrl: 'that.html' } )
  .when( '/other', { templateUrl: 'other.html' } )
  .otherwise( { redirectTo: '/this' } );
});

app.controller( 'MainCtrl', function ( $scope ) {
});

对于 1.2(大概是更高版本)失败了。

当 AngularJS 1.2 发布时 ngRoute 已移入其自己的模块中。这意味着您需要包含一个单独的文件才能使路由在 AngularJS 1.2 以上工作。这意味着要做的第一件事是包含 angular-route.js 文件,就像包含任何其他脚本一样

<script src="angular-route.js">

其次,包含对您的应用程序模块的依赖。

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

最后,您可以像在上面的代码中那样配置 $routeProvider

app.config(function($routeProvider){
    $routeProvider
      .when('/',{
          template: '<h1>Work</h1><a href="#/test">Test Route</a>'
      })
      .when('/test',{
          template: '<h1>Test</h1><a href="#/">Back</a>'
      })
      .otherwise({ 
        template: '<h1>Not Found</h1>'
      });
});

这就是路由背后的整个设置魔法。这是一个有效的 example.

编辑 1:

如果您使用的是 bower,您可以通过以下方式获取模块:

bower install angular-route