######$route被用于URLS到controller和view(HTML模板)之间的链接,它会监控$location.url()并试图对此路径及对应的路由配置进行映射,使用时需要安装ngroute模块:
在模板主页header上添加:
<pre><code> <script src="../js/angular-route.min.js"></script></code></pre>
index.html:
<pre></code> <!doctype html> <html xmlns:ng="http://angularjs.org" ng-app='app' ng-csp="" scroll id="ng-app"> <head> <meta charset="UTF-8"> <title>angularjs route</title> <link rel="stylesheet" href="../css/bootstrap.css"/> <script src="../js/angular.min.js"></script> <script src="../js/angular-animate.min.js"></script> <script src="../js/angular-route.min.js"></script> <script src="../js/main.js"></script> </head> <body> <div class="header"> <a href="#/">主页</a><a href="#/other">其他页</a> </div> <div ng-view class="main"></div> </body> </html> </code></pre>
other.html:
<pre><cdoe><h1>{
{title}}</h1></code></pre>home.html:
<pre><cdoe><h1>{
{title}}</h1></code></pre>使用方式为,在main.js中添加:
<pre><code> var app = angular.module('app', [ 'ngRoute' ]) .config(function ($routeProvider){ $routeProvider .when('/other', { controller: 'otherCtrl', templateUrl: 'content/views/other.html', publicAccess: true }) .when('/', { controller: 'homeCtrl', templateUrl: 'content/views/home.html' }) .when('/other/:id', { controller: 'otherDetailCtrl', templateUrl: 'content/views/otherDetail.html', publicAccess: true }) .otherwise({ redirectTo: '/' }); } app.controller('homeCtrl',function($scope,$http){ console.log('i am home page'); $scope.title = 'i am home page'; }).controller('otherCtrl',function($scope){ console.log('i am other page'); $scope.title = 'i am other page'; }).controller('otherDetailCtrl',function($scope, $routeParams, $location){ var id = $routeParams.id; if(id == 0) { $location.path('/other'); } console.log('i am otherDetailCtrl page'); $scope.title = 'i am otherDetailCtrl page'; }); </code></pre>
当打开index.html时,会自动打开'/',当点击导航中“主页”、“其他页”时,会进行页面切换。
在$route(路由)中,提供了两个依赖性服务:$location、$routeParams; $location、$routeParams均可在controller中使用,如上otherDetailCtrl中,可通过$routeParams获取路由时所传参数,可通过$location进行路由跳转。