gpt4 book ai didi

javascript - Angularjs orderBy 无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-04 16:19:42 24 4
gpt4 key购买 nike

我修改了 angularjs 文档中给出的示例。我在该示例中为所有年龄字段设置了零,当我单击年龄排序按钮时,列表正在排序(不知道列表是根据哪个参数进行排序的),尽管所有年龄字段都为零并且不应该已排序。

Plunker: https://plnkr.co/edit/85dmPRFu6IPhHnTkXqgU?p=preview

查看:

<div ng-controller="ExampleController">
<pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
<hr />
<button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
<hr />
<table class="friends">
<tbody>
<tr>
<th>
<button ng-click="sortBy('name')">Name</button>
<span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
</th>
<th>
<button ng-click="sortBy('phone')">Phone Number</button>
<span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
</th>
<th>
<button ng-click="sortBy('age')">Age</button>
<span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</tbody>
</table>
</div>

Controller :

.controller('ExampleController', ['$scope', function($scope) {
var friends = [
{name: 'John', phone: '555-1212', age: 0},
{name: 'Mary', phone: '555-9876', age: 0},
{name: 'Mike', phone: '555-4321', age: 0},
{name: 'Adam', phone: '555-5678', age: 0},
{name: 'Julie', phone: '555-8765', age: 0}
];

$scope.propertyName = 'age';
$scope.reverse = true;
$scope.friends = friends;

$scope.sortBy = function(propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
$scope.propertyName = propertyName;
};
}

最佳答案

在 angularjs 的底层使用 this function :

function doComparison(v1, v2) {
for (var i = 0, ii = predicates.length; i < ii; i++) {
var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
if (result) {
return result * predicates[i].descending * descending;
}
}

return compare(v1.tieBreaker, v2.tieBreaker) * descending;
}

由于您的 v1v2 始终相同,因此 compare(v1.tieBreaker, v2.tieBreaker) 将始终返回相同的值-1 (因为 v1.value 等于 v2.value,所以使用了 tieBreaker),而 descending 变量根据排序顺序,将为 -11。这就是 Angular 变化顺序的原因。

如果您不在此过滤器中使用sortOrder:

friend in friends | orderBy:propertyName:reverse

或者每次点击这里都没有改变:

$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;

顺序不会改变。

关于javascript - Angularjs orderBy 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40757815/

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