angular路由操作

在单页面应用程序中比如angular应用,我们需要根据url的变化(即:不同的请求),来分配不同的资源。根据请求的URL来决定执行哪个模块,这个过程叫路由,同时,我们需要设计路由规则。

下面给出一个简单的小demo:

html结构:

<body ng-app='rootApp'>
  <ul>
    <li><a href='#/'>主页</a></li>
    <li><a href='#/floor1'>一楼</a></li>
    <li><a href='#/floor2'>二楼</a></li>
  </ul>
  <!-- ng-view 渲染站位 -->
  <div ng-view></div>
</body>
<!-- 引入angular包 -->
<script src='bower_components/angular/angular.js'></script>
<!-- 引入angular-route包 -->
<script src='bower_components/angular-route/angular-route.js'></script>
<!-- 下面是渲染模板 -->
<script id='tmpl' type='text/ng-template'>
  <h1>{{placeholder}}</h1>
</script>

js结构:

  /* 此处定义模块,由于需要设定路由,所以要注入ngRoute */
  var rootApp = angular.module('rootApp', ['ngRoute']);
  /* 定义路由表(路由规则)*/
  rootApp.config(['$routeProvider', function($routeProvider) {
    /* $routeProvider 就相当于交通警察,根据when和otherwise指挥路由走向 */
    $routeProvider
      .when('/', {
        // 当请求的“URL” / , 找当前定义控制器和视图
        controller: 'DefaultController',
        /* template: '<h1>{{hello}}</h1>' */
        templateUrl: 'tmpl'
      })
      .when('/floor1/1', {
        controller: 'Floor1',
        templateUrl: 'tmpl'
      })
      /* 这里用:id这种形式来保存路由参数,以便后来用$routeParams可以取到 */
      .when('/floor2/:id/:name/:age', {
        controller: 'Floor2',
        templateUrl: 'tmpl'
      })
      .otherwise({
        /* 都不匹配,定向到根目录 */
        redirectTo: '/'
      });
  }]);

    // 定义相关控制器
    rootApp.controller('DefaultController', ['$scope', function($scope) {
      $scope.placeholder= '当前为主页';
    }]);
    rootApp.controller('Floor1', ['$scope', function($scope) {
      $scope.placeholder = '当前为1楼';
    }]);
    rootApp.controller('Floor2', ['$scope', '$routeParams', function($scope, $routeParams) {
      /* $routeParams 用于解析请求参数 */
      console.log($routeParams);
      $scope.placeholder= '当前为2楼';
    }]);

总结: 
angular中的路由需要使用它的ngRoute模块,具体使用方法如上所示,其中路由表的设计是通过模块配置$routeProvider的when和otherwise来处理不同的请求参数。 
其中ng-view用于占坑,when中的template或者是templateUrl用于渲染控制层定义的数据,去填这个坑,其中路由参数是根据:parmName 来指定,通过$routeParams来解析参数。

posted @ 2017-01-18 11:21  BlueSky1024  阅读(156)  评论(0编辑  收藏  举报