angularjs $route(路由) 的使用

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

在模板主页header上添加:

 

index.html:

 
        angularjs route
        

 

 
        
        
        
        
    
    
    

 

 
 
 
 
  
  
  
  
主页 其他页

other.html:

 
 
  
 
  

{{title}}

home.html:

 
 
  
 
  

{{title}}

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


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';
});

当打开index.html时,会自动打开'/',当点击导航中“主页”、“其他页”时,会进行页面切换。

在$route(路由)中,提供了两个依赖性服务:$location、$routeParams;
$location、$routeParams均可在controller中使用,如上otherDetailCtrl中,可通过$routeParams获取路由时所传参数,可通过$location进行路由跳转。

你可能感兴趣的:(angularjs $route(路由) 的使用)