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

时间:2017-01-24 03:19:43

标签: angularjs angular-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,我无法找到源代码。不确定是否有人有类似的问题,可以指出我如何解决这个问题?感谢。

1 个答案:

答案 0 :(得分:0)

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只是一种捷径。