2018-09-04

AngularJS 路由学习地址

then方法.png

路由的应用
ui.router
通过调用$stateProvider.state()方法创建了一个简单的路由规则,包括匹配的URL和对应的模板,当我们访问http://xxxx#/abc的时候,路由规则被匹配到,对应的模板会被填到div[ui-view]中。
$stateProvider.state()方法:
1.创建并存储一个state对象,里面包含该路由规则的所有配置信息。
2.调用$urlRouterProvider.when(...)方法,进行路由的注册
当hash值与state.url相匹配的时候,就跳到该state
路由是怎么匹配的:

  1. angular在刚开始$digest时,$rootScope会触发$locationChangeSuccess 事件(angular在浏览器每次hash change的时候也会触发$locationChangeSuccess事件)
  2. ui.router监听了$locationChangeSuccess事件,于是开始通过便利一系列的rules,进行路由匹配查找
  3. 当匹配到路由后,就通过$state.transitionTo(state,…),跳转激活对应的state
  4. 最后,完成数据请求和模板的渲染

    
        
        AngularJS 路由实例 - W3Cschool教程
    
    
     
        

AngularJS 路由应用

实例解析:

  1. 载入了实现路由的 js 文件:angular-route.js;
  2. 包含了 ngRoute 模块作为主应用模块的依赖模块;
    angular.module('routingDemoApp',['ngRoute'])
  3. 使用 ngView 指令;

    该 div 内的 HTML 内容会根据路由的变化而变化。
    配置 $routeProvider,AngularJS $routeProvider用来定义路由规则。
module.config(['$routeProvider', function($routeProvider){
    $routeProvider
        .when('/',{template:'这是首页页面'})
        .when('/computers',{template:'这是电脑分类页面'})
        .when('/printers',{template:'这是打印机页面'})
        .otherwise({redirectTo:'/'});
}]);

AngularJS 模块的 config 函数用于配置路由规则。通过使用 configAPI,我们请求把$routeProvider注入到我们的配置函数并且使用$routeProvider.whenAPI来定义我们的路由规则。
$routeProvider为我们提供了 when(path,object) & otherwise(object) 函数按顺序定义所有路由,函数包含两个参数:

  • 第一个参数是 URL 或者 URL 正则规则。
  • 第二个参数是路由配置对象。

路由设置对象
AngularJS 路由也可以通过不同的模板来实现。
$routeProvider.when 函数的第一个参数是 URL 或者 URL 正则规则,第二个参数为路由配置对象。
路由配置对象语法规则如下:

$routeProvider.when(url, {
    template: string,
    templateUrl: string,
    controller: string, function 或 array,
    controllerAs: string,
    redirectTo: string, function,
    resolve: object
});

参数说明:

  • template:
    如果我们只需要在 ng-view 中插入简单的 HTML 内容,则使用该参数:
    .when('/computers',{template:'这是电脑分类页面'})
  • templateUrl:
    如果我们只需要在 ng-view 中插入 HTML 模板文件,则使用该参数:
    $routeProvider.when('/computers', { templateUrl: 'views/computers.html', });
    以上代码会从服务端获取 views/computers.html 文件内容插入到 ng-view 中。
  • controller:
    function、string或数组类型,在当前模板上执行的controller函数,生成新的scope。
  • controllerAs:
    string类型,为controller指定别名。
  • redirectTo:
    重定向的地址。
  • resolve:
    指定当前controller所依赖的其他模块。










  
  

  


你可能感兴趣的:(2018-09-04)