Bộ lọc orderBy của AngularJS

Định nghĩa và cách sử dụng

orderBy Bộ lọc cho phép chúng ta sắp xếp mảng.

Mặc định, các chuỗi được sắp xếp theo thứ tự alphabet, số được sắp xếp theo thứ tự số.

Trang liên quan

Hướng dẫn AngularJS:Bộ lọc Angular

Mô hình

Ví dụ 1

Hiển thị các mục theo thứ tự alphabet:

<div ng-app="myApp" ng-controller="orderCtrl">
<ul>
<li ng-repeat="x in cars | orderBy">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
    $scope.cars = ["Dodge", "Fiat", "Audi", "Volvo", "BMW", "Ford"];
]];
);

</script>

Ví dụ 2

Sắp xếp theo "city" của mảng:
<div ng-app="myApp" ng-controller="orderCtrl">
<ul>
<li ng-repeat="x in customers | orderBy : 'city'">{{x.name + ", " + x.city}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
    $scope.customers = [
        {"name": "Bottom-Dollar Marketse", "city": "Tsawassen"},
        {"name": "Alfreds Futterkiste", "city": "Berlin"},
        {"name": "Bon app", "city": "Marseille"},
        {"name": "Cactus Comidas para llevar", "city": "Buenos Aires"},
        {"name": "Bolido Comidas preparadas", "city": "Madrid"},
        {"name" : "Around the Horn", "city" : "London"},
        {"name" : "Around the Horn", "city" : "London"}
    {"name" : "B's Beverages", "city" : "London"}
]];
);

</script>

Ví dụ 3

Sắp xếp giảm dần theo "city" của mảng:
<div ng-app="myApp" ng-controller="orderCtrl">
<ul>
<li ng-repeat="x in customers | orderBy : '-city'">{{x.name + ", " + x.city}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
    $scope.customers = [
        {"name": "Bottom-Dollar Marketse", "city": "Tsawassen"},
        {"name": "Alfreds Futterkiste", "city": "Berlin"},
        {"name": "Bon app", "city": "Marseille"},
        {"name": "Cactus Comidas para llevar", "city": "Buenos Aires"},
        {"name": "Bolido Comidas preparadas", "city": "Madrid"},
        {"name" : "Around the Horn", "city" : "London"},
        {"name" : "Around the Horn", "city" : "London"}
    {"name" : "B's Beverages", "city" : "London"}
]];
);

</script>

Thử ngay

Cú pháp {{ array Mô tả | orderBy : Mảng: Nếu cần nhiều thuộc tính của đối tượng để xác định thứ tự sắp xếp, hãy sử dụng mảng. Các mục của mảng có thể là chuỗi và hàm. :

}}

}} Parameter
Mô tả

expression

Cập nhật để xác định thứ tự. Cập nhật có thể là các loại sau:

Chuỗi: Nếu mảng là mảng đối tượng, bạn có thể sắp xếp mảng theo giá trị của một thuộc tính của đối tượng. Xem ví dụ trên.

Hàm: Bạn có thể tạo một hàm để tổ chức sắp xếp.

Mảng: Nếu cần nhiều thuộc tính của đối tượng để xác định thứ tự sắp xếp, hãy sử dụng mảng. Các mục của mảng có thể là chuỗi và hàm. reverse