2015-11-27 13 views
0

如何通過單擊下一個按鈕和前一個單擊上一個按鈕來轉到下一個項目?通過單擊ng-repeat外的按鈕移動到下一個和上一個項目AngularJS

重複,以顯示從數據庫數據:

idSelectedShipment是所選擇的股利或貨物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] 
     }; 

回答

2

它看起來像你的目標是使「當前」重複元素的selected_trip類,和你的背部/下一個按鈕改變呢?

根據目前你有什麼,你需要在你nextback功能做的就是相應地改變的idSelectedShipment的價值,但我認爲這可能不是最佳的前進道路。

棘手的部分是,您的基礎數據結構shipments是爲視圖排序的。您的控制器和ngRepeat塊以外的範圍不會意識到這一點。出於這個原因,你不能真正使用$index有意義。

我會推薦的是在控制器中預先排序你的數組,然後跟蹤當前的索引位置。您的代碼可能會看起來像以下:

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> 
+0

感謝@cnw您的回覆讓我試試這個,我會讓你知道 – usama

+0

感謝的人我認爲它正在工作,但我現在得到排序問題,它不工作。以前我的排序代碼 $ scope.sortType ='shipment_id'; $ scope.predicate ='created_at'; ng-repeat =「發貨裝運| orderBy:謂詞:反向」 $ scope.reverse = false; $ scope.order = function(predicate){ $ scope.reverse =($ scope.predicate ===謂詞)? !$ scope.reverse:false; $ scope.predicate = predicate; }; – usama

+0

也是$ scope.reverse = false; $ scope.predicate ='created_at'後面; @cmv – usama

相關問題