如何通过单击“下一个”按钮转到下一个项目以及通过单击“上一个”按钮转到上一个项目?
重复显示数据库中的数据:
idSelectedShipment 是所选的 div 或货件 ID
<div ng-repeat="shipment in shipments | orderBy:predicate:reverse">
<div ng-click="show_shipment($index,shipment.shipment_id)" ng-class="{selected_trip: shipment.shipment_id == idSelectedShipment}">
<div> From {{shipment.from_location}}</div>
</div>
</div>
下一个和上一个按钮:
<a class="" ng-click="next($event)" href="#">next</a>
<a class="" ng-click="previous($event)" href="#">previous</a>
我在这部分遇到了麻烦。下一个按钮和上一个按钮位于 ng-repeat 之外,我似乎无法在单击时传递索引。
$scope.next= function(index){
[index + 1]
};
$scope.previous= function(index){
[index - 1]
};
最佳答案
看起来您的目标是在“当前”重复元素上渲染 selected_trip
类,而您的后退/下一步按钮会更改此设置吗?
根据您当前的情况,您需要在 next
和 back
函数中执行的操作是更改 idSelectedShipment
的值因此,但我认为这可能不是最好的前进方式。
棘手的部分是您的基础数据结构,shipments
,是针对 View 进行排序的。您的 Controller 和 ngRepeat
block 之外的范围不会意识到这一点。因此,您无法真正有意义地使用 $index
。
我建议在 Controller 中对数组进行预排序,然后跟踪当前索引位置。您的代码可能如下所示:
function MyController ($scope, $filter) {
$scope.sortedShipments = $filter('orderBy')($scope.shipments, 'predicate', true);
$scope.currentShipment = 0;
$scope.back = function () {
if ($scope.currentShipment > 0) {
$scope.currentShipment--;
}
};
$scope.next = function () {
if ($scope.currentShipment < $scope.sortedShipments.length - 1) {
$scope.currentShipment++;
}
};
}
然后将 HTML 更改为...
<div ng-repeat="shipment in sortedShipments">
<div ng-click="foo()" ng-class="{selected_trip: $index === currentShipment}">
<div> From {{shipment.from_location}}</div>
</div>
</div>
关于javascript - 通过单击 ng-repeat AngularJS 外部的按钮移至下一个和上一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964179/