【问题标题】:AngularJS + SwipeJS not working without setTimeout of 0 millisecondsAngularJS + SwipeJS 在 setTimeout 为 0 毫秒的情况下无法工作
【发布时间】:2014-07-22 12:59:14
【问题描述】:

我正在编写一个 AngularJS 指令,它可以让我轻松地创建可滑动的页面(例如 Android 上的 viewpager)。我使用SwipeJS 作为这个库。

这就是我使用指令的方式

<ng-swipe ng-if="model.messages">
    <div class="page" ng-repeat="message in model.messages">
        {{message.title}}
    </div>
</ng-swipe>

指令的代码如下所示。

var swipe = angular.module('ngSwipe', []);

swipe.directive('ngSwipe', function() {
    return {
        restrict: 'EA',
        replace: false,
        transclude: true,
        scope: {},
        template:
                '<div>' +
                '    <div id="slider" class="swipe">' +
                '        <div class="swipe-wrap" ng-transclude></div>' +
                '    </div>' +
                '    <div class="pagecontrol">' +
                '        <div class="pagedot" ng-repeat="p in swipe.pages" ng-click="swipe.switchPage($index)"></div>' +
                '    </div>' +
                '</div>',
        link: function($scope, $element, $attrs) {
            var $model = $scope.swipe = {
                pages: [],
                switchPage: function(index) {
                    $model.swipe.slide(index);
                }
            }

            setTimeout(function() {
                $model.swipe = new Swipe(document.getElementById('slider'), {
                    continuous: false,
                    callback: function(index, elem) {
                        $model.currentTab = index;
                    }
                });

                for(var i=0; i<$model.swipe.getNumSlides(); i++) {
                    $model.pages.push(i);
                }

                $scope.$apply();
            }, 0);
        }
    };
});

首先,我在 ng-swipe 指令中使用 ng-if 的原因是因为应该在我的消息加载后调用链接方法。正在从服务器检索消息,最多可能需要 2 秒才能检索到这些消息。如果我不等到消息加载完毕,则会创建新的 Swipe() 对象,但它不会找到页面,因此无法工作。

但除此之外,您还可以看到我有一个 0 毫秒的 setTimeout() 函数。如果我不使用那个,它就不会呈现滑动页面。

我为此问题创建了JSFiddle。提前致谢!

【问题讨论】:

    标签: angularjs angularjs-directive settimeout swipe


    【解决方案1】:
    switchPage: function(index) {
      $model.swipe.slide(index);
      $scope.$apply();
    }
    

    【讨论】:

    • 问题不是分页不起作用,问题是当我删除 setTimeout() 包装函数时页面没有被呈现。您可以更改 JSFiddle 以对其进行测试。
    猜你喜欢
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 2021-06-09
    • 1970-01-01
    • 2012-04-01
    • 2022-01-11
    相关资源
    最近更新 更多