您的位置:首页 > Web前端 > AngularJS

AngularJS $route路由

2016-05-21 23:43 369 查看
前段时间的项目用到了AngularJS route,在获取URL参数传变量过程中遇到了些问题,顺利解决了,趁着周末总结一下,分享之。

路由配制方法

一般来说,路由配置方法的形式如下所示:

angular.module("sportsStore", ["ngRoute"])
.config(function ($routeProvider) {

$routeProvider.when("/welcome", {
templateUrl: "/views/welcome.html"
});

$routeProvider.when("/thank", {
templateUrl: "/views/thankyou.html"
});

$routeProvider.otherwise({
templateUrl: "/views/main.html"
});
});
通过.confg(function($routeProvider){}) 方法进行设置。然后通过添加when函数,设置模板url。
otherwise方法表示,如果任何其它方法都匹配不到,将匹配otherwise里面的。

路由配置View的使用

通过$routeProvider定义好路由模式之后,默认是不会添加到HTML的视图当中。需要通过<ng-view />命令,方能引入$routeProvider的视图路由。如下:

<body ng-controller="myCtrl">
    <div class="navbar navbar-inverse">
        <a class="navbar-brand" href="#">mainpage</a>
    </div>
    <div class="navbar navbar-inverse">
        <a class="navbar-brand" href="#/thank">thankyou</a>
    </div>
    <div class="navbar navbar-inverse">
        <a class="navbar-brand" href="#/welcome">welcome</a>
    </div>
    <ng-view />
</body>
用ng-view接收对应的视图模板,给$route对应的视图占位,可以根据配置来放置。

URL的配置

$stateProvider
.state("login",{
url:"/login",
templateUrl: "/pages/login.html"
})

当我们访问index.html/login时, 'login'状态将被激活,同时index.html中的ui-view将被'login.html'填充。或者,通过transitionTo('login')方法将状态转变到'login'状态,同时 url 将更新为index.html/login。

URL的参数

用:或者子页面的参数传送:
$stateProvider
.state("appdetail",{
url:"/app/:instance",
templateUrl: "/pages/app.detail.html"
})
module.controller('DCtrl', function($stateParams) {
$stateParams; // has instance
}

//A  A.B类型的子页面的参数
$stateProvider.state("component", {
url: "/:apphost/:instance/:id",
templateUrl: "/pages/component.info.html"
});
module.controller('ACtrl', function($stateParams) {
$stateParams; // has apphost, instance, and id
}

$stateProvider.state("component.jvminfo",{
url:"/jvminfo",
templateUrl: "/pages/jvm.info.html",
params: {
"component": "虚拟机",
"componenten":"jvminfo"
}       //可定义参数传送
});
module.controller('ABCtrl', function($stateParams) {
$stateParams; // has apphost, instance, id, component, and componenten
}

带?的指定参数:
$stateProvider.state("component", {
url: "/component?myParam",
templateUrl: "/pages/component.info.html"
});

module.controller('DCtrl', function($stateParams) {
$stateParams; // has myParam
}

$stateProvider.state("component", {
url: "/component?myParam1&myParam2",
templateUrl: "/pages/component.info.html"
});

module.controller('DCtrl', function($stateParams) {
$stateParams; // has myParam1, myParam2
}

具体实例:
// 如果状态中 url 属性是:
url: '/users/:id/details/{type}/{repeat:[0-9]+}?from&to'

当浏览:'/users/123/details//0'
$stateParams 对象将是{ id:'123', type:'', repeat:'0' }

当浏览'/users/123/details/default/0?from=there&to=here'
$stateParams 对象将是{ id:'123', type:'default', repeat:'0', from:'there', to:'here' }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  angularjs route url