使用 Onsen 从轮播中移除项目 UI

Removing Items from carousel with Onsen UI

我有一个使用 Onsen 的简单应用程序 UI,我正在利用轮播并根据用户向左或向右滑动到当前轮播元素来更新数据。一旦他们刷过,我想从轮播中删除该元素,这样他们就无法再次访问它。 我正在尝试使用似乎工作正常的 postchange 事件,但是当我调用 carousel.refresh() 时,轮播没有更新。

轮播在html中是这样定义的:

<ons-carousel var="carousel" swipeable overscrollable auto-scroll fullscreen initial-index="1">
  <ons-carousel-item ng-repeat="foo in bar.baz">
  ....
  </ons-carousel-item>
</ons-carousel>

因为轮播是在第一个页面以外的页面上初始化的,所以我添加了一个事件处理程序来监视是否有新页面被推送到导航控制器上,如果它是带有轮播的页面,然后为轮播的 postchange 事件初始化一个处理程序并更新一些东西。我已针对此示例对其进行了简化。

ons.ready(function(){
  mainNavigator.on('postpush', function(event){
    var page = event.enterPage;
      if (page.name == "carousel_page.html"){
        carousel.on('postchange', function(event){
          $scope.bar.baz.splice(event.lastActiveIndex, 1);
          setImmediate(function(){
            // even setting the array to [] here does not make a difference
            carousel.refresh();
          });
        });
      }
    });
  });

逐步执行所有操作,我可以验证传送带后面的数组是否已正确更新并且传送带变量定义正确,并且调用了 refresh(),但我的传送带从未更新。我在这里错过了什么?

我在 Onsen 中使用 Angular,这是不是因为我添加事件处理程序的方式所致?它是在 $digest 循环之外还是什么?

这里有一个错误列表...ons-carousel 是在上一个版本的 OnsenUI 中发布的,它只被测试用于静态数量的元素和一些其他功能,但不是这样.一切都会在几周后的下一个版本中修复。

如果您还想尝试一些东西,这可能会给您一些想法:

$scope.carousel.on('postchange', function(event){
    $scope.$apply(function() {
        $scope.bar.baz.splice(event.lastActiveIndex, 1);
    });
    setImmediate(function(){
        carousel.refresh();
    });
});

现在应该删除并刷新,但由于一些错误行为,slideDistance 可能是错误的。要解决此问题,您可以考虑使用

$scope.carousel.setActiveCarouselItemIndex($scope.carousel.getActiveCarouselItemIndex());

紧接在 carousel.refresh(); 之后,但这会再次触发 'postchange' 事件...

要避免此 'postchange' 事件问题,您可以多做一些 angular-like:

// Let's do something when the ActiveCarouselItemIndex changes
$scope.$watch(function(){return $scope.carousel.getActiveCarouselItemIndex()}, function(newIndex,oldIndex){
    if (newIndex !== oldIndex) {
        $scope.bar.baz.splice(oldIndex, 1);
        setImmediate(function(){
            $scope.carousel.refresh();
            // Avoid the position problem
            $scope.carousel.setActiveCarouselItemIndex($scope.carousel.getActiveCarouselItemIndex());
        });
    }
});
// Still necessary
$scope.carousel.on('postchange', function(event){
    $scope.$apply();
    return;
});

这看起来比上一个好,但仍然有点问题...您可能会找到修改它并解决问题的方法,但等待下一个版本可能会更容易关注动态轮播。

希望对您有所帮助!