6.1 路由的作用
6.1.1 路由允许我们通过不同的 URL访问不同的内容
6.1.2 可以实现多视图的单页Web应用(singlepage web application,SPA)
6.1.3 单页Web应用中 AngularJS通过 # +标记 实现,例如:http://runoob.com/#/first
6.2 使用
6.2.1 解析
6.2.1.1 载入了实现路由的 js文件:angular-route.js。
6.2.1.2 包含了ngRoute模块作为主应用模块的依赖模块。
6.2.1.3 使用ngView指令
6.2.1.4 配置$routeProvider,AngularJS $routeProvider用来定义路由规则。
6.2.1.5 AngularJS 模块的 config函数用于配置路由规则。通过使用 configAPI,我们请求把$routeProvider注入到我们的配置函数并且使用$routeProvider.whenAPI来定义我们的路由规则。
使用:<div ng-view></div>
定义:
angular.module('routingDemoApp',['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/',{template:'这是首页页面'})
.when('/computers',{template:'这是电脑分类页面'})
.when('/printers',{template:'这是打印机页面'})
.otherwise({redirectTo:'/'});
}]);
when参数一:url或者utl正则表达式
when参数二:路由配置对象
6.3 路由配置对象参数
$routeProvider.when(url, {
template: string,
templateUrl: string,
controller: string, function 或 array,
controllerAs: string,
redirectTo: string, function,
resolve: object<key, function>
});
参数说明:
template:如果我们只需要在 ng-view 中插入简单的 HTML 内容,则使用该参数:
.when('/computers',{template:'这是电脑分类页面'})
templateUrl: 如果我们只需要在 ng-view 中插入 HTML 模板文件,则使用该参数:
.when('/computers', {templateUrl: 'views/computers.html'})
controller: function、string或数组类型,在当前模板上执行的controller函数,生成新的scope
controllerAs: string类型,为controller指定别名。
redirectTo: 重定向的地址
resolve: 指定当前controller所依赖的其他模块。