orderBy 来自 ng-repeat 的字段,带有 ui-sortable

orderBy a field from ng-repeat with ui-sortable

我正在使用 ui-sortable 在 2 个对象数组之间进行拖放,我需要在拖放后按名称字段对数组中的对象进行排序。

这是我在 html 文件中的代码:

<body ng-controller="listCtrl">
  <ul ui-sortable="playerConfig" ng-model="players">
    <li ng-repeat="player in players">
      <!--| orderBy: ['name']-->
      {{player.name}}
    </li>
  </ul>
</body>

 <style type="text/css">
     .beingDragged {
    height: 24px;
    margin-bottom: .5em !important;
    border: 2px dotted #ccc !important;
    background: none !important;
 }
 </style>

在控制器中:

angular.module('app', [
    'ui.sortable'
]).

controller('listCtrl', function ($scope) {

  var baseConfig = {
      placeholder: "beingDragged"
  };

  $scope.playerConfig = angular.extend({}, baseConfig, {
      connectWith: ".players"
  });

  $scope.players = [
      { 
        "name" : "John",
        "id" : "123",
        "score": "456"
      },
      { 
        "name" : "Tom",
        "id" : "234",
        "score": "678"
      },
      { 
        "name" : "David",
        "id" : "987",
        "score": "5867"
      }
   ];

我做了一些搜索,发现 github 中报告的类似问题为 https://github.com/angular-ui/ui-sortable/issues/70,但是,Plunker 代码使用了我无法找到源代码的 orderByFilter。不确定是否有人有类似的问题,可以指出我如何解决这个问题?谢谢

orderByFilter 是 AngularJS 的一部分,因此您已经可以访问它了。

就像你找到的例子一样,你可以将它注入你的控制器并使用它:

app.controller('MyController', function ($scope, orderByFilter) {

  $scope.players = [{ name: 'Eve'}, { name: 'Adam'}];

  $scope.sorted = orderByFilter($scope.players, 'name');
});

这相当于:

app.controller('MyController', function ($scope, $filter) {

  $scope.players = [{ name: 'Eve'}, { name: 'Adam'}];

  var orderByFilter = $filter('orderBy');
  $scope.sorted = orderByFilter($scope.players, 'name');
});

或者只是:

$scope.sorted = $filter('orderBy')($scope.players, 'name');

直接注入 orderByFilter 而不是 $filter 只是一种捷径。