对ng-repeat进行排序

时间:2022-12-02 16:37:00

I am trying to sort a client list using ng-repeat in Angular so that the column with ratings "Hot", "Warm", and "Cold" presented in that order. Currently when it sorts the Rating column it puts them in alphabetical order of "Cold", "Hot", and "Warm". How would I sort it non-alphabetically like that? Is it something with using a custom directive to create a custom attribute related to the rating value and then using "track by"?

我正在尝试使用ng-repeat来对客户列表进行排序,以便按照这个顺序对评级为“Hot”、“Warm”和“Cold”的列进行排序。目前,当它对评级列进行排序时,它将它们按字母顺序排列为“Cold”、“Hot”和“Warm”。我怎么能不按字母顺序排序呢?是否使用自定义指令创建与评级值相关的自定义属性,然后使用“track by”?

Here is a CodePen with a working example of how it sorts alphabetically:

下面是一个代码页,其中有一个按字母顺序排序的示例:

http://codepen.io/MattSchultz/pen/VeBpaQ

http://codepen.io/MattSchultz/pen/VeBpaQ

<li id="listCont" ng-repeat="client in clients | orderBy:col:reverse as results" ng-class-even="'even'">
    <ul class="clients">
      <li>{{client.Name}}</li>
      <li>{{client.AnnualRevenue | currency}}</li>
      <li ng-class="classy('{{client.Rating}}')">{{client.Rating}}</li>
    </ul>
</li>

1 个解决方案

#1


3  

If you pass a string (i.e. an object property name) as the first argument to the orderBy filter, as you are doing in your example, it will attempt to sort alphabetically. To change this behavior, you need to pass a custom sort function instead.

如果您将字符串(例如对象属性名)作为orderBy过滤器的第一个参数传递给它,就像您在示例中所做的那样,它将尝试按字母顺序排序。要更改此行为,您需要传递自定义排序函数。

For example:

例如:

function ratingSort(val) {
  return ['Cold', 'Warm', 'Hot'].indexOf(val.Rating);
};

This function returns a number between -1 (i.e. val.Rating value is not in the array) and 2 (i.e. 'Hot', which is at index 2 in the array). The number returned is used to determine the sort order.

这个函数返回-1(即value . rating值不在数组中)和2(即)之间的数字。'Hot',在数组的索引2处)。返回的数字用于确定排序顺序。

Here is a working example: CodePen

这里有一个工作示例:CodePen

#1


3  

If you pass a string (i.e. an object property name) as the first argument to the orderBy filter, as you are doing in your example, it will attempt to sort alphabetically. To change this behavior, you need to pass a custom sort function instead.

如果您将字符串(例如对象属性名)作为orderBy过滤器的第一个参数传递给它,就像您在示例中所做的那样,它将尝试按字母顺序排序。要更改此行为,您需要传递自定义排序函数。

For example:

例如:

function ratingSort(val) {
  return ['Cold', 'Warm', 'Hot'].indexOf(val.Rating);
};

This function returns a number between -1 (i.e. val.Rating value is not in the array) and 2 (i.e. 'Hot', which is at index 2 in the array). The number returned is used to determine the sort order.

这个函数返回-1(即value . rating值不在数组中)和2(即)之间的数字。'Hot',在数组的索引2处)。返回的数字用于确定排序顺序。

Here is a working example: CodePen

这里有一个工作示例:CodePen