Angularjs中ng-repeat與移動端滑動外掛iScroll的衝突
阿新 • • 發佈:2019-02-08
IScroll是在移動端開發的過程中會經常使用到的一個外掛,但當其與angularjs中的ng-repeat指令配合使用時,很有可能會導致iScroll外掛失效或者滑動不正常,另外當ng-repeat迴圈的列表動態增加時也會導致滑動不正常。
滑動不正常原因:
1.在ng-repeat未將列表迴圈展示出來時,iScroll便被啟動了,導致滑動異常,因此需要確保ng-repeat迴圈完畢後再初始化iScroll
2.在動態的向ng-repeat迴圈列表中新增內容後,需要重新設定滑動區域#scroller的寬度,然後重新初始化一下iScroll外掛
html 程式碼
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Title</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>