我正在尝试使用AngularJS构建一个轮播组件,我在stackoverflow上找到了this example。
下一个函数按预期工作,但是当我尝试对前一个函数执行相同操作时,它在达到0时进入负值,循环到-3,然后跳回到0.
有人可以解释% $scope.pages.length
究竟做了什么,以及它是如何运作的?我试过谷歌搜索,但没有找到任何解释。
我的控制员:
.controller('portfolioController', function($scope) {
$scope.pages = [
{
image: "/../images/Placeholder.jpg",
alt: "thumbnail first page",
name : "1",
description : "Moj Prvi Webpage",
active : 1
},
{
image: "/../images/Placeholder.jpg",
alt: "thumbnail first page",
name : "2",
description : "Moj Drugi Webpage",
active : 0
},
{
image: "/../images/Placeholder.jpg",
alt: "thumbnail first page",
name : "3",
description : "Moj Tretji Webpage",
active : 0
},
{
image: "/../images/Placeholder.jpg",
alt: "thumbnail first page",
name : "4",
description : "Moj Četrti Webpage",
active : 0
}
];
$scope.current = 0;
$scope.Next = function() {
$scope.current = ($scope.current + 1) % $scope.pages.length;
}
$scope.Previous = function() {
$scope.current = ($scope.current - 1) % $scope.pages.length;
}
});
我的HTML:
<div class="col-xs-12">
<div class="thumbnail">
<img ng-src="{{ pages[current].image }}" alt="{{ pages[current].alt }}">
<div class="caption">
<h3>{{ pages[current].name }}</h3>
<p>{{ pages[current].description }}</p>
</div>
</div>
<div class="row carousel-thumbnails">
<div class="col-xs-12">
<div class="btn btn-info" ng-click="Previous()">Previous</div>
<img ng-repeat="img in pages" ng-class="{'active': img.active}" src="{{ img.image }}" alt="{{ img.alt }}">
<div class="btn btn-info" ng-click="Next()">Next</div>
</div>
</div>
</div>
答案 0 :(得分:1)
有问题的行是modulo (or remainder) operation。它取第一个值,除以第二个值,然后返回余数。
$scope.Previous
无法正常工作的原因是,一旦达到零,它将开始返回负数,而不是返回到最大值(在这种情况下,该值将为$scope.pages.length - 1
。避免这种情况,尝试这样的事情(问号是ternary/conditional operator:
$scope.current = $scope.current == 0 ? ($scope.pages.length - 1) : ($scope.current - 1)
这是一个有效的jsfiddle