如果没有0毫秒的setTimeout,AngularJS + SwipeJS无法正常工作

时间:2014-07-22 12:59:14

标签: angularjs angularjs-directive settimeout swipe

我正在编写一个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的原因是因为在加载消息后应该调用link方法。正在从服务器检索消息,并且在检索它们之前最多可能需要2秒钟。如果我不等待,直到加载消息,将创建新的Swipe()对象,但它不会找到页面,因此它将无法工作。

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

我为此问题制作了JSFiddle。提前谢谢!

1 个答案:

答案 0 :(得分:0)

switchPage: function(index) {
  $model.swipe.slide(index);
  $scope.$apply();
}