Blog

Blog

PHODAL

Ionic Android应用开发《程序语言答人》——Router

在上一篇Ionic Android应用开发《程序语言答人》中简单地介绍了一下开始的流程,接着我们来说说Router。

UI Router

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. Unlike the $route service in the Angular ngRoute module, which is organized around URL routes, UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

有这样的一个中文介绍

AngularUI Router是AngularJS的路由框架,和默认的$route不同,它将所有路由包装成可划分层级的状态机状态,路由路径在ui-router中不是必须的。由于ui-router的路由状态机是分层级的,所以使用ui-router可以非常方便地创建包含多个嵌入的子模板。

一个简单的路由如下所示:

.state('app', {
    url: "/app",
    abstract: true,
    templateUrl: "templates/menu.html"
})

即有URL、模板,而对于一个复杂的Ionic的Router来说是这样子的

    .state('app.wiki', {
    url: "/wiki",
    views: {
        'menuContent': {
            templateUrl: "templates/wiki.html",
            controller: 'WikiCtrl'
        }
    }
})

即带有Controller,一个完整的Router还会有一个默认的路由

$urlRouterProvider.otherwise('/app/level');

Router路由

/app/level对应的路由是:

.state('app.levelSelect', {
  url: "/level",
  views: {
    'menuContent': {
      templateUrl: "templates/level.html",
      controller: 'LevelSelectCtrl'
    }
  }
})

level.html的内容如下所示:

<ion-view view-title="选择级别">
  <ion-content>
    <ion-list>
      <ion-item ng-repeat="level in levels" href="#/app/level/{{level.id}}">
          <div ng-if="level.id == 1 ">
              <i class="icon ion-ios-unlocked"></i> &nbsp;{{level.title}}
          </div>
          <div ng-if="level.id != 1 ">
              <i class="icon ion-ios-locked"></i> &nbsp;{{level.title}}
          </div>
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

LevelSelectCtrl如下所示:

.controller('LevelSelectCtrl', function ($scope) {
    if (typeof analytics !== 'undefined') {
        analytics.trackView("LevelSelectCtrl");
    }
    $scope.levels = [
        {title: 'Level 1', id: 1},
        {title: 'Level 2', id: 2},
        {title: 'Level 3', id: 3},
        {title: 'Level 4', id: 4}
    ];
})

Controller做的事,似乎就是将数据放到模板,接着渲染~~,就会有如下的结果。

ScreentShot

当我们选择level1时,逻辑就来到了

  .state('app.single', {
    url: "/level/:level",
    views: {
      'menuContent': {
        templateUrl: "templates/level_quiz.html",
        controller: 'QuizCtrl'
      }
    }
  })

这就是一个简单的页面间的跳转与Router的关系。

其他

代码: https://github.com/phodal/learning-ionic

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签