在Angular订购后错误的$ index

时间:2016-01-20 10:50:35

标签: angularjs-ng-repeat angularjs-orderby

在ng-repeat中订购商品后出现问题。点击项目打开页面后索引错误。 我的示例HTML代码,打开页面正确:

<div ng-repeat="item in items" ng-click="showPost($index)">{{item.title}}</div>

如果添加orderby,则显示错误的帖子索引:

<div ng-repeat="item in items | orderBy:'-title'" ng-click="showPost($index)">{{item.title}}</div>

我的$ scope函数showPost():

  $scope.showPost = function(index){
    $rootScope.postContent = $scope.catItems[index];
    $scope.ons.navigator.pushPage('post.html');
  };

1 个答案:

答案 0 :(得分:0)

我认为问题在于ngRepeat中的数组顺序(在应用orderBy过滤器之后)与$ scope.catItems的顺序不同。

通过将对象本身作为函数参数传递并在数组中查找对象而不是传递索引来修复代码会更好。 假设$ scope.items和$ scope.catItems是不同的数组,请尝试类似的事情:

// HTML
<div ng-repeat="item in items | orderBy:'-title'" ng-click="showPost(item)">{{item.title}}</div>
// JS

$scope.showPost = function(item){
    var index = $scope.items.indexOf(item);
    $rootScope.postContent = $scope.catItems[index];
    $scope.ons.navigator.pushPage('post.html');
  };