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進行路由跳轉。

相關文章
相關標籤/搜索