我有一个像这样的对象数组:
$scope.businesses = [
{ name: 'BusinessName', cost: '12' },
{ name: 'AnotherBusinessName', cost: '79-122' },
{ name: 'LastBusinessName', cost: '120' }
];
我正在尝试使用
orderBy
按成本排序,如下所示:<ul>
...
<li ng-click="sortProps('-cost')">Price: High to Low</li>
</ul>
用
sortProps
这样声明:$scope.sortProps = function(prop) {
$scope.sortBy = prop;
$scope.reverse = false;
};
出于某种原因,当按
'-cost'
(或其相反)进行订购时,我总是得到12> 120> 79-122显示。当按
'-cost'
排序时,我希望看到120> 79-122>12。我知道问题出在哪里(代价是对象中的字符串),但我不确定如何将其转换为Number
,同时仍显示完整的价格范围,例如79-122。我在构造我的
parseFloat(business.cost)
时尝试过$scope.businesses
,但是这会除去-
之后的所有内容,这是可以预期的。但奇怪的是,这仍然给了我12> 120> 79(从79-122解析)的排序顺序。我也尝试过类似的方法:
$scope.sortProps = function(prop) {
if (prop === 'cost' || prop === '-cost') {
angular.forEach($scope.businesses, function(business) {
business.cost = parseFloat(business.cost);
});
}
// ...
};
以便在按成本排序时仅将其转换为数字。我迷路了,有什么建议吗?
最佳答案
该解决方案包括两个部分:
使用“ costNum”属性(为数字)“标记”数据”
通常在该新属性上使用orderBy过滤器。
这是plunker
的JavaScript
(function(){
'use strict';
angular.module('app', []).controller('TestCtrl', Controller);
function Controller($scope){
$scope.orderByProp = null;
$scope.sort = function() {
$scope.orderByProp = 'costNum';
};
$scope.reverseSort = function() {
$scope.orderByProp = $scope.orderByProp === 'costNum' ? '-costNum' : 'costNum';
};
$scope.removeSort = function() {
$scope.orderByProp = null;
};
$scope.businesses = [
{name: 'Business Zero', cost: '345'},
{name: 'Business One', cost: '12'},
{name: 'Another Two', cost: '79-122'},
{name: 'Business Three', cost: '120'},
{name: 'Business Four', cost: '20'},
{name: 'Business Five', cost: '80'}
];
function markupBiz() {
for(var i = 0, len = $scope.businesses.length; i < len; i++) {
$scope.businesses[i].costNum = parseFloat($scope.businesses[i].cost);
}
}
markupBiz();
}
})();
的HTML
<div ng-controller="TestCtrl">
<button ng-click="sort()">Sort</button>
<button ng-click="reverseSort()">Reverse sort</button>
<button ng-click="removeSort()">Remove sort</button>
<ul>
<li ng-repeat="business in businesses | orderBy:orderByProp">
{{business.name}}: ${{business.cost}}
</li>
</ul>
</div>