gpt4 book ai didi

javascript - 使用 orderBy 进行 Angularjs 排序对我来说不起作用

转载 作者:行者123 更新时间:2023-11-28 00:35:50 25 4
gpt4 key购买 nike

我正在尝试根据评级、定价和总数对我的家庭列表进行排序。不幸的是,我不为我工作,我是 angularjs 的新手。这是我的 html 代码。事实上,它正在对事物进行排序,但不是按顺序排列。->当用户点击价格按钮时,他应该先以最高价格回家,然后是更低价格、最低价格等(5000,4000,3000),如果他再次点击,则订单必须是(3000,4000,5000)。总计数和评级的情况类似。我还创建了 plunker 来编辑您的建议。请编辑并向我提供工作链接。这是 demoForEdit

//html code
<body ng-controller="MainCtrl as ctrl">
<div class="col-md-offset-2">
<button ng-click="orderByPopularity='total_counts'; reverseSort = !reverseSort" class="btn btn-sm btn-info">sort on total counts </button>
<button ng-click="orderByPopularity='price'; reverseSort = !reverseSort" class="btn btn-sm btn-danger">sort on Price</button>
<button ng-click="orderByPopularity='avg'; reverseSort = !reverseSort" class="btn btn-sm btn-success">sort on ratings</button>
</div>
<br>
<div ng-repeat="home in homes | orderBy:orderByPopularity:reverseSort">
<div class="panel panel-primary ">
<div class="panel-heading">
Home name: {{home.home_name}}
</div>
<div class="panel-body">
<div class="panel panel-body">
<table>
<p>total counts:{{home.total_counts}}</p>
<p>city:{{home.city}}</p>
<p>Price:{{home.price}}</p>
<div ng-repeat="rate in rating">
<!-- looping inside ng-repeat rating is seprate data but has home id-->
<div ng-if="rate.home_id==home.id">
Home raintgs:{{rate.avg}}
</div>
</div>
</div>
</div>
</div>
</div>

//My app.js code
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.homes=[{"id":"48","home_name":"Swastik","city":"Banglore","zipcode":"888888","total_counts":"1","price":"5000"},
{"id":"49","home_name":"Khushboo","city":"Chennai","zipcode":"456786","total_counts":"17","price":"3333"},
{"id":"50","home_name":"Raj","city":"Hydrabad","zipcode":"123455","total_counts":"2","price":"20000"}];
$scope.orderByPopularity ='total_counts';
$scope.reverseSort = true;
$scope.rating=[{"home_id":"48","avg":"3.5"},
{"home_id":"49","avg":"2"},
{"home_id":"50","avg":"4"}
];
});

最佳答案

它确实排序,但您的 total_counts 值是字符串,因此它按字典顺序对它们进行排序。如果您想按数字排序(我假设您这样做),则需要删除引号并将其值作为数字本身,即: "total_counts":17 等。

编辑:进行修改,以便您可以将值保留为字符串(在自定义排序函数内)。

至于 avg 评级排序,您不能这样做,因为您的排序位于 $scope.homes 上,并且此数组的对象没有 avg 属性,这是另一个数组的属性 - $scope. ratings。要按该属性排序,您必须创建自己的自定义函数。

$scope.myValueFunction = function(o) {

if ($scope.orderByPopularity == "avg") {
var obj;
for (var i = 0; i < $scope.rating.length; i++) {
if ($scope.rating[i].home_id == o.id) {
obj = $scope.rating[i]
}
}
return obj.avg;
}
else {
return parseInt(o[$scope.orderByPopularity]);
}

};

在 HTML 中:

<div ng-repeat="home in homes | orderBy:myValueFunction:reverseSort">

看看这个Plunker至于演示。

关于javascript - 使用 orderBy 进行 Angularjs 排序对我来说不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28514785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com