5

この質問でランダムorderByソート手法を使用すると、AngularJS 1.1 で問題なく動作します。

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
    $scope.random = function() {
        return 0.5 - Math.random();
    }
}

ただし、1.2 ではinfdigコンソールにエラーが表示され、並べ替えられた結果を返すのに非常に長い時間がかかります: http://jsfiddle.net/mblase75/jVs27/

コンソールのエラーは次のようになります。

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: $watchCollectionWatch; newVal: 42; oldVal: 36"],["fn: $watchCollectionWatch; newVal: 47; oldVal: 42"],["fn: $watchCollectionWatch; newVal: 54; oldVal: 47"],["fn: $watchCollectionWatch; newVal: 61; oldVal: 54"],["fn: $watchCollectionWatch; newVal: 68; oldVal: 61"]]

のドキュメントにorderByは、関数式の使用例はなく、文字列式のみです。何か変更がありましたか、それともバグですか?

4

2 に答える 2

2

シンプルなカスタム フィルターを使用して、Angular の方法でこれを解決できます。ここでは、Fischer-Yates を実装するアンダースコア シャッフル メソッドを使用しています。

必要に応じて、シャッフルの内臓を独自のアルゴリズムに置き換えることができます。

angular.module('shuffle', [])
  .filter('shuffle', function() {
    return function(ary) {
      return _.shuffle(ary);
    }
  });

次のように、このフィルターを介して配列をパイプできます。

<li ng-repeat='option in options | shuffle'>

フィルターは、テンプレートがレンダリングされるときに 1 回呼び出されます。

于 2014-11-13T18:10:17.863 に答える