Comment faire fonctionner le filtre orderby sur un tableau de chaînes?

85

Voici le code qui ne fonctionne pas: Démo: http://jsfiddle.net/8dt94/63/

<div ng-controller="MyCtrl">    
    <input type="text" ng-model="searchText" />
  <ul ng-repeat="strVal in arrVal|orderBy|filter:searchText" >
      <li>{{strVal}}</li>
  </ul>
</div>

var app=angular.module('myApp', []);
app.controller('MyCtrl', function ($scope,$filter) {
  $scope.arrVal = ['one','two','three','four','five','six'];  
});
SunnyShah
la source
Je ne crois pas que vous devriez utiliser des valeurs primitives dans votre tableau ng-repeat. Sinon ça marche. ( jsfiddle.net/EGVwG ).
Tosh
Cette question s'applique toujours aux ng-options attr d'un select, qui doit être une liste de chaînes.
Train d'Espagne le

Réponses:

248

Vous pouvez commander par une méthode, vous pouvez donc utiliser la méthode toString

<ul ng-repeat="strVal in arrVal | orderBy:'toString()' | filter:searchText">
notclive
la source
+1. De plus, vous pouvez ajouter "track by" à la fin: <ul ng-repeat = "strVal in arrVal | orderBy: 'toString ()' | filter: searchText track by $ index">
Amy
9
Excellente solution, j'avais besoin d'un tableau de nombres triés comme ça, [2,5,3,1,6, 33]alors à la place, toString()j'ai utilisé valueOf()et cela a fonctionné parfaitement. Merci pour la solution.
ug_
Cela a fonctionné pour moi aussi! Une idée de pourquoi cette astuce fonctionne?
elethan
11

Écrivez un filtre personnalisé :

app.filter('mySort', function() {
    return function(input) {
      return input.sort();
    }
  });

HTML:

<ul ng-repeat="strVal in arrVal|filter:searchText|mySort">

Violon .

Mark Rajcok
la source