【问题标题】:Move to next and previous item by clicking on buttons outside the ng-repeat AngularJS通过单击 ng-repeat AngularJS 之外的按钮移动到下一个和上一个项目
【发布时间】:2015-11-27 20:02:48
【问题描述】:

如何点击下一个按钮进入下一个项目,点击上一个按钮进入上一个项目?

重复显示数据库中的数据:

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]
       };

【问题讨论】:

    标签: javascript jquery angularjs


    【解决方案1】:

    看起来您的目标是在“当前”重复元素上呈现 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>
    

    【讨论】:

    • 感谢@cnw 的回复让我试试这个,我会告诉你的
    • 谢谢伙计,我认为它正在工作,但我遇到了排序问题,现在它不工作了。这是我之前的排序代码 $scope.sortType = 'shipment_id'; $scope.predicate = 'created_at'; ng-repeat="shipment in shipping | orderBy:predicate:reverse" $scope.reverse = false; $scope.order = function(predicate) { $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse:假; $scope.predicate = 谓词; };
    • 他们也是 $scope.reverse = false;在 $scope.predicate = 'created_at' 之后; @cmv
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多