我希望我的li元素被隐藏,当我的状态加载时,我只想显示前两个元素,而当我单击按钮o时,则显示接下来的两个元素,依此类推。
这是应该如何工作的:
http://jsfiddle.net/zuyvgwx3/2/
在我的有角度的应用程序中,我显示li元素,如下所示:
<ul id="myList">
<li ng-repeat="offre in offres |orderBy:'-dateCreation'|filter:{etat:'true'}">
<div class="box">
<!-- HTML Code -->
</div>
</li>
</ul>
我将li元素设置为display:none;
并显示了前两个元素的javascript代码如下:
<script>
size_li = $("#myList li").size();
x=2;
$('#myList li:lt('+x+')').show();
$('#loadMore').click(function () {
x= x+2;
$('#myList li:lt('+x+')').show();
});
</script>
问题是,当我的状态加载时,显示了所有li元素,而不仅显示了前两个元素,正如您在我附加的小提琴中所看到的那样,它可以工作,但是当我将其与ng-repeat一起使用时,它却无法工作。
我该如何解决?
使用Angular时,应尽量避免以这种方式直接操作DOM。相反,在这种情况下,您应该利用Angular指令来控制元素的显示方式ng-show
。
您已经将列表存储在中$scope.offres
。您只需要跟踪要显示的项目数,并且仅在$index
可用项目ng-repeat
低于该值时才显示它:
angular.module('myapp', []).controller('ctrl1', function($scope) {
// set up the list with dummy data
$scope.offres = [];
for (var i = 0; i < 11; i++) {
$scope.offres.push(i + 1);
}
// set initial index
// we will use this variable to control the display - see ng-show="" in HTML
$scope.loadIndex = 2;
// function to increase visible items
$scope.showMore = function() {
// don't increment if at the end of the list
if ($scope.loadIndex < $scope.offres.length) {
$scope.loadIndex += 2;
}
};
// function to decrease visible items
$scope.showLess = function() {
// don't decrement if at the start of the list
if ($scope.loadIndex > 2) {
$scope.loadIndex -= 2;
}
};
});
#loadMore {
color: green;
cursor: pointer;
}
#loadMore:hover {
color: black;
}
#showLess {
color: red;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="ctrl1">
<ul id="myList">
<li ng-repeat="offre in offres" ng-show="$index < loadIndex">{{offre}}</li>
</ul>
<div id="loadMore" ng-click="showMore()">Load more</div>
<div id="showLess" ng-click="showLess()">Show less</div>
</div>
如您所见,然后实现显示较少的项目就变得微不足道了,因为您只需要在控制器中更改一个数字即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句