在访问带有列表的页面,一般会点击列表中某行记录,访问其详情页面,点击返回后回到列表页面,若不进行定位,那么用户需要重新滚动直到找到刚才点击的行记录,体验不好。那么返回时定位可以将刚才点击的行记录直接展示在当前的可视区域内。
ionic中列表定位可以通过$ionicScrollDelegate来实现,定位方式:
1、通过锚点定位
2、通过滚动高度定位
两种方式的实现都需要考虑列表是否渲染完成的问题,方式1通过元素id,方式2通过滚动高度,因此列表未渲染完成会导致定位的元素id不存在或者滚动的高度不够的问题而使定位失效。那么监听列表渲染是否完成可以通过自定以指令来做,如下:
app.directive('onWatchRepeatFinished',function ($timeout) {
return {
restrict: 'A',
link: function(scope,element,attr) {
if (scope.$last === true) {
var key=attr.onWatchRepeatFinished;
if(key!=null) {
key=key.replace(/(^\s*)|(\s*$)/g,"");
if(key==="") {
key="ngRepeatFinished";
}
} else {
key="ngRepeatFinished";
}
$timeout(function() {
scope.$emit(key);
});
}
}
};
});
***********************定位方式1:通过锚点定位**************************
////////////////////页面/////////////////////
<ion-content
delegate-handle="
businessList
-handle">
<div class="list">
<div class="item"
ng-repeat="info in infos"
ng-click="gotoInfoDetail($index)"
id="info-anchor-{{$index}}"
on-watch-repeat-finished="businessList">
{{info.date}}
</div>
</div>
</ion-content>
////////////////////controller/////////////////////
$scope.
gotoInfoDetail
=function(index) {
$window.localStorage['
info
-anchor']='
info-anchor-
'+index;
//跳转到详情
$scope.gotoView.gotoNewHospDetailPage();
}
$scope.$on('
businessList
',function (e) {
var anchorid=$window.localStorage['
info
-anchor'];
if(!$Element.isEmpty(anchorid)) {
$location.hash(anchorid);
$ionicScrollDelegate.$getByHandle('
businessList
-handle
').anchorScroll();
$window.localStorage['
info
-
scroll
']=null;
}
});
***********************定位方式2:通过滚动高度定位**************************
////////////////////页面/////////////////////
<ion-content
delegate-handle="
businessList
-handle">
<div class="list">
<div class="item"
ng-repeat="info in infos"
ng-click="gotoInfoDetail()"
on-watch-repeat-finished="businessList">
{{info.date}}
</div>
</div>
</ion-content>
////////////////////controller/////////////////////
$scope.
gotoInfoDetail
=function() {
var handle=$ionicScrollDelegate.$getByHandle('
businessList
-handle
');
if(handle) {
$window.localStorage['
info
-scroll']=
handle.getScrollPosition().top;
}
$window.localStorage['
info
-scroll']=0
;
//跳转到详情
$scope.gotoView.gotoNewHospDetailPage();
}
$scope.$on('
businessList
',function (e) {
var
scrolltop
=$window.localStorage['
info
-
scroll
'];
if(!$Element.isEmpty(
scrolltop
)) {
$ionicScrollDelegate.$getByHandle('
businessList
-handle
').scrollTo(0,parseInt(
scrolltop
));
$window.localStorage['
info
-
scroll
']=null;
}
});