angularjs $route(路由) 的使用

######$route被用于URLS到controller和view(HTML模板)之间的连接,它会监控$location.url()并试图对此路径及对应的路由配置进行映射,使用时须要安装ngroute模块:css

在模板主页header上添加:html

<pre><code> &lt;script src="../js/angular-route.min.js">&lt;/script></code></pre>angularjs

index.html:bootstrap

<pre></code> &lt;!doctype html> &lt;html xmlns:ng="http://angularjs.org" ng-app='app' ng-csp="" scroll id="ng-app"> &lt;head> &lt;meta charset="UTF-8"> &lt;title>angularjs route&lt;/title> &lt;link rel="stylesheet" href="../css/bootstrap.css"/> &lt;script src="../js/angular.min.js">&lt;/script> &lt;script src="../js/angular-animate.min.js">&lt;/script> &lt;script src="../js/angular-route.min.js">&lt;/script> &lt;script src="../js/main.js">&lt;/script> &lt;/head> &lt;body> &lt;div class="header"> &lt;a href="#/">主页&lt;/a>&lt;a href="#/other">其余页&lt;/a> &lt;/div> &lt;div ng-view class="main">&lt;/div> &lt;/body> &lt;/html> </code></pre>app

other.html:ide

<pre><cdoe>&lt;h1>{{title}}&lt;/h1></code></pre>url

home.html:code

<pre><cdoe>&lt;h1>{{title}}&lt;/h1></code></pre>xml

使用方式为,在main.js中添加:htm

<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进行路由跳转。

相关文章
相关标签/搜索