angular路由


AngularJS 路由允许我们通过不同的 URL 访问不同的内容。 AngularJS 模块的 config 函数用于配置路由规则。通过使用 configAPI,我们请求把$routeProvider注入到我们的配置函数并且使用$routeProvider.whenAPI来定义我们的路由规则。 $routeProvider 为我们提供了 when(path,object) & otherwise(object) 函数按顺序定义所有路由,函数包含两个参数: 第一个参数是 URL 或者 URL 正则规则。 第二个参数是路由配置对象。

$routeProvider.when(url, { template: string, templateUrl: string, }) .otherwise({redirectTo: string});

$routeParams.id==存储数据url值 {{$index}}当前选中下表

template:如果我们只需要在 ng-view 中插入简单的 HTML 内容,则使用该参数: templateUrl:如果我们只需要在 ng-view 中插入 HTML 模板文件,则使用该参数: redirectTo:重定向的地址。 路由功能是由 routeProvider服务 和 ng-view 搭配实现,ng-view相当于提供了页面模板的挂载点,当切换URL进行跳转时,不同的页面模板会放在ng-view所在的位置; 然后通过 routeProvider 配置路由的映射。


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>luyou</title>
<script type="text/javascript" src="../lib/angular1.min.js"></script>
<script type="text/javascript" src="../lib/angular-route.js"></script>
</head>
<body ng-app="app">
<div>
<a href="#home">首页</a>
<a href="#about">关于</a>
<a href="#other">其他</a>
</div>
<div ng-view></div>
</body>
<script type="text/javascript">
angular.module('app',['ngRoute'])
.config(['$routeProvider',function ($routeProvider) {
$routeProvider
.when('/home',{
controller:'ctrl-home',
templateUrl:'template/home.html'
})
.when('/about',{
controller:'ctrlList',
templateUrl:'template/about.html'
})
.when('/other',{
controller:'ctrlOther',
templateUrl:'template/other.html'
})
.when('/list/:id',{
controller:'ctrl-li',
templateUrl:'template/list.html'
})
.otherwise({redirectTo:'/home'})
}])
.controller('ctrl-home',function ($scope) {
$scope.aaa='home页的字符串'
})
.controller('ctrlList',function ($scope,$http) {
$http({
method:'get',
url:'demo.json'
}).success(function (data) {
$scope.arr=data;
})
})
.controller('ctrlOther',function ($scope) {
$scope.arr=['订单','dd','哈哈哈','凤飞飞'];
})
.controller('ctrl-li',function ($scope,$http,$routeParams) {
$http({
method:'get',
url:'demo.json'
}).success(function (data) {
$scope.str=data[$routeParams.id].con
}
)
})
</script>
</html>
原文地址:https://www.cnblogs.com/guozhenzhen/p/7123167.html