我有一个像这样的对象数组:
$scope.cars = [
{"brand":"McLaren","price":70,"stock":0},
{"brand":"Renault","price":10,"stock":0},
{"brand":"Ferrari","price":100,"stock":3},
{"brand":"Lamborghini","price":50,"stock":2},
{"brand":"Porsche","price":30,"stock":1},
{"brand":"Seat","price":120,"stock":0},
{"brand":"Audi","price":10,"stock":3},
];
我想在 Angular 中按照我的观点从高价到低价对它们进行排序,但保留最后有 "stock":0
的那些。有没有什么直接的方法可以用 Angular 来做到这一点?这是一个working plunker以我为例。谢谢!
最佳答案
放弃比较器功能,我们可以按“stock == 0”排序,因为按字符串排序是 Angular 表达式。这比我最初的比较器解决方案简单得多。
`orderBy:['stock==0','-price']`
http://plnkr.co/edit/HUHaHLwCR4rkLvHm6K0u?p=preview
li p {
font-family:Arial;
color:black;
}
.noStock p {
font-family:Arial;
color:gray;
font-style:italic;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="myCtrl" ng-app="myApp">
<p>{{title}}</p>
<ul>
<li ng-repeat="car in cars | orderBy:['stock==0','-price']" ng-class="{'noStock':car.stock==0}">
<p>{{ car.brand }} ({{ car.price }}) <span ng-if="car.stock==0">Out of Stock</span></p>
</li>
</ul>
</div>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.title ="Cars";
$scope.cars = [
{"brand":"McLaren","price":70,"stock":0},
{"brand":"Renault","price":10,"stock":0},
{"brand":"Ferrari","price":100,"stock":3},
{"brand":"Lamborghini","price":50,"stock":2},
{"brand":"Porsche","price":30,"stock":1},
{"brand":"Seat","price":120,"stock":0},
{"brand":"Audi","price":10,"stock":3},
];
});
</script>
</body>
</html>
关于javascript - Angular JS - orderBy 一个键,同时在另一个键为 0 时保持最终结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45845265/