Angularjs中ng-repeat与移动端滑动插件iScroll的冲突

IScroll是在移动端开发的过程中会经常使用到的一个插件,但当其与angularjs中的ng-repeat指令配合使用时,很有可能会导致iScroll插件失效或者滑动不正常,另外当ng-repeat循环的列表动态增加时也会导致滑动不正常。

滑动不正常原因:
1.在ng-repeat未将列表循环展示出来时,iScroll便被启动了,导致滑动异常,因此需要确保ng-repeat循环完毕后再初始化iScroll
2.在动态的向ng-repeat循环列表中添加内容后,需要重新设置滑动区域#scroller的宽度,然后重新初始化一下iScroll插件

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>qdabc.cn</title>
    <script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/iScroll/5.2.0/iscroll.min.js"></script>
    <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        #wrapper {
            position: absolute;
            z-index: 1;
            width: 100%;
            height: 100px;
            top:0;
            left:0;
        }

        #scroller {
            position: absolute;
            z-index: 1;
            width: 500px;
            height: 100%;
        }
        ul {
            width: 100%;
            height: 100%;
            text-align: center;
        }
        li {
            display: block;
            float: left;
            width: 100px;
            height: 100%;
            line-height: 100px;
        }
    </style>
</head>
<body ng-controller="myCtrl">

<div>
    <div id="wrapper">
        <div id="scroller">
            <ul>
                <li ng-repeat="item in names track by $index">
                    {{item}}
                </li>
            </ul>
        </div>
    </div>

    <button ng-click="addItem()" style="margin-top: 350px">add</button>
</div>

<script>
    var app = angular.module('myApp', []);

    app.controller('myCtrl', ['$scope', function ($scope) {
        $scope.names = [1, 2, 3, 4, 5];
        $scope.count = 6;
        $scope.addItem = function () {
            $('#scroller').css('width', $scope.count * 100 + 'px');
            $scope.names.push($scope.count++);
            //loaded(); 或者使用下面的方法
            if (myScroll) {
                myScroll.refresh();
            }
        };

        var myScroll;
        window.onload = function () {
            loaded();
        };
        function loaded() {
            myScroll = new IScroll('#wrapper', {
                scrollX: true,
                scrollY: false,
                mouseWheel: true
            });
        }
    }]);

</script>
</body>
</html>

欢迎分享本文,转载请保留出处:前端ABC » Angularjs中ng-repeat与移动端滑动插件iScroll的冲突

分享到:更多 ()

发表评论 0