什么可以快速,快速地重新排序UI列表?

时间:2016-07-27 20:31:10

标签: html angularjs html5 typescript angular

我正在使用Angular 2&打字稿。

在我的项目中,我提供了一个简单的json对象列表,html看起来像这样:

<div>
  <!-- Present List Button -->
  <button md-button
          (click)="showList()"
          class="md-primary"
          title="show list">Cropping</button>
</div>


<md-content>
  <div *ngIf="showList">
  <div class="list-bg"  *ngFor="#list of lists | async">
    ID: {{list.id}} <p></p> Number of Items: {{list.numberOfItems}}
  </div>
  </div>
</md-content>

非常简单的清单。

现在我想要某种方法来重新排序这个列表,并将lists数组设置为新的顺序。

我正在寻找一种方法,用户可以根据需要对列表进行重新排序,例如按优先级更改列表。

有人可以帮我找一个快速实施的方法并且效果很好吗?

(我研究了一些拖放库,但是我使用了Angular 2(2.0.0-beta.15)的特定版本,而不支持它们。)

感谢分配!

1 个答案:

答案 0 :(得分:0)

为此您必须使用角度2管道以获取更多信息,请检查this

  

orderBy Pipe

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: "orderBy",
  pure: false,
})

export class OrderBy implements PipeTransform {
  transform(array: any, args: any) {
    if (array != null) {
      if (array) {
        let orderByValue = args;
        let byVal = 1
        if (orderByValue.charAt(0) == "!") {
          byVal = -1
          orderByValue = orderByValue.substring(1)
        }


        array.sort((a: any, b: any) => {
          if (a[orderByValue].toString().toLowerCase() < b[orderByValue].toString().toLowerCase()) {
            return -1 * byVal;
          } else if (a[orderByValue].toString().toLowerCase() > b[orderByValue].toString().toLowerCase()) {
            return 1 * byVal;
          } else {
            return 0;
          }
        });
        return array;
      }
    }
  }
}
  

<强>组件

import {Filter} from '../pipes/filter';
import {OrderBy} from '../pipes/orderBy';

@Component({
  selector: 'category',
  templateUrl: '../views/category.component.html',
  directives: [ROUTER_DIRECTIVES],
  providers: [SetupService, HTTP_PROVIDERS],
  pipes: [ OrderBy]
})
  

查看升序

<md-content>
  <div *ngIf="showList">
  <div class="list-bg"  *ngFor="#list of lists | async | orderBy:'id'">
    ID: {{list.id}} <p></p> Number of Items: {{list.numberOfItems}}
  </div>
  </div>
</md-content>
  

查看降序

<md-content>
  <div *ngIf="showList">
  <div class="list-bg"  *ngFor="#list of lists | async | orderBy:'!id'">
    ID: {{list.id}} <p></p> Number of Items: {{list.numberOfItems}}
  </div>
  </div>
</md-content>