Why are my ng-repeat items not filtering as expected here?

我是研究僧i 提交于 2020-01-04 13:44:46

问题


Plnkr: http://plnkr.co/edit/Q34J9szbLeGgc4jkcNUM?p=preview

I have a simple Array called tags, which contains 4 objects with a tweets value and vol value.

When I click the Order by Tweets, or Order by Vol buttons I expect the numbers to make sense, like going from high to low or low to high, but the numbers are out of order.

Markup:

 <div class="sidebar" ng-controller="sidebar">
  <header class="my-header">
    <button ng-click="reOrderByTweets()">Order by Tweets</button>
    <button ng-click="reOrderByVol()">Order by Vol</button>
  </header>
  <ul>
    <li ng-repeat="t in tags" ng-mouseleave="leaveTag(t)">
      <div class="tag-container">
        <div class="tag border1"
             ng-mouseover="showTagDetails(t)">{{t.name}} | tweets: {{t.tweets}} | vol: {{t.vol}}</div>
        <tag-details tag="t"></tag-details>
      </div>
    </li>
  </ul>
</div>

JavaScript:

$scope.tags.push(
  {
    name: 'Item 1 ', 
    tweets: '412',
    vol: '50'
  },
  {
    name: 'Item 2 ', 
    tweets: '10',
    vol: '500'
  },
  {
    name: 'Item 3 ', 
    tweets: '67',
    vol: '5'
  },
  {
    name: 'Item 4 ', 
    tweets: '0',
    vol: '30'
  }
);

The functions:

function reOrderByTweets() {
    console.log('reOrderByTweets');
    vs.orderReverse = !vs.orderReverse;
    $scope.tags = $filter('orderBy')($scope.tags, 'tweets', vs.orderReverse);
    console.log('vs.orderReverse = ', vs.orderReverse); // true or false
    console.log('$scope.tags = ', $scope.tags);
}

function reOrderByVol() {
    console.log('reOrderByVol');
    vs.orderReverse = !vs.orderReverse;
    $scope.tags = $filter('orderBy')($scope.tags, 'vol', vs.orderReverse);
    console.log('vs.orderReverse = ', vs.orderReverse); // true or false
    console.log('$scope.tags = ', $scope.tags);
}

As you can see the screenshot below, while ordering by Vol. The item with vol:5 should come last after vol:30


Update: Looks like it's only filtering on the first digit in the numbers? Why would it not take the entire number?

Filtering by tweets clicked once:

Filtering by tweets clicked a 2nd time:


回答1:


You're ordering by a string value which is done by alphabetical order.

'10' '5' '30'

The string order of this is 10 / 30 / 5.

Changing your 'vol' & 'tweets' to numbers:

  $scope.tags.push(
    {
      name: 'Item 1 ', 
      tweets: 412,
      vol: 50
    },
    {
      name: 'Item 2 ', 
      tweets: 10,
      vol: 216
    },
    {
      name: 'Item 3 ', 
      tweets: 67,
      vol: 15
    },
    {
      name: 'Item 4 ', 
      tweets: 0,
      vol: 30
    }
  );

Sorts your tweets correctly.



来源:https://stackoverflow.com/questions/32298987/why-are-my-ng-repeat-items-not-filtering-as-expected-here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!