使用Tabs和SlideBox实现左右滑动菜单
1.将tab1.html的代码改为如下:
<ion-view view-title="健康"> <ion-content class="has-header"> <ion-slide-box show-pager="false" class="has-header" on-slide-changed="slideChanged($index)"> <ion-slide ng-repeat="slide in slides"> <div class="list"> <a ng-repeat="item in tabs" class="item item-thumbnail-left" href="#"> <img ng-src="img/TongeBlog.jpg" width="30" height="30" alt=""> <h2>title:{{slide.name}}</h2> <p>description</p> </a> </div> </ion-slide> </ion-slide-box> </ion-content> <ion-tabs class="tabs-striped tabs-top"> <ion-tab ng-repeat="item in tabs" on-select="selectedTab($index)" title="{{item.name}}"></ion-tab> </ion-tabs> </ion-view>
2.service层的Tab1Service
angular.module('starter.services', []) .service('Tab1Service', function ($http) { this.getClassify = function () { return [ { name: '健康资讯', viewable: true, url: domain + '/info/list', page: 1, rows: 20 }, { name: '健康知识', viewable: false, url: domain + '/lore/list', page: 1, rows: 20 }, { name: '健康问答', viewable: false, url: domain + '/ask/list', page: 1, rows: 20 }, { name: '健康图书', viewable: false, url: domain + '/book/list', page: 1, rows: 20 } ] } this.getList = function (url, page, rows) { return $http.post(url, { page: page, rows: rows }) } });
3.完善对应的Tab1Ctrl
.controller('Tab1Ctrl', function ($scope, Tab1Service, $ionicSlideBoxDelegate, $ionicTabsDelegate) { var items = Tab1Service.getClassify() $scope.slides = items; $scope.tabs = items; var slideIndex = 0; $scope.slideChanged = function (index) { $ionicTabsDelegate._instances[1].select(index); }; $scope.$on('$ionicView.afterEnter', function () { $ionicTabsDelegate._instances[1].select($ionicSlideBoxDelegate.currentIndex()); }); $scope.selectedTab = function (index) { //滑动的索引和速度 $ionicSlideBoxDelegate.slide(index) } })
4.代码解释
上面菜单部分使用了Tab组建,中间的列表部分使用SlideBox,并不存在任何嵌套,只是在各自选择的时候做一些处理。
Tab1Service:使用依赖注入,来调用服务层获取数据。
slideChange:slidebox选择的时候将tab对应的索引选中。
selectedTab:选中tab的时候,将对应的slidebox选中。
ionicView.afterEnter:在页面加载完成的时候默认让tab的第一个项选中。
_instances[1]:是因为该项目中用了两个tab,[1]才是取的第二个。
完!