我修改了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('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;
};
}
答案 0 :(得分:1)
引擎盖下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;
}
由于您的v1
和v2
始终相同,compare(v1.tieBreaker, v2.tieBreaker)
将始终返回相同的值-1
(因为v1.value
等于{{1}使用了tieBreaker,而v2.value
变量将是descending
或-1
,具体取决于排序顺序。这就是角度变化的顺序。
如果您在此过滤条件中不使用1
:
sortOrder
或者每次点击都没有改变:
friend in friends | orderBy:propertyName:reverse
订单不会改变。
答案 1 :(得分:0)
输出背后的实际原因是当您点击年龄过滤器时,数据将不再排序。它按照控制器中声明的保存顺序显示您的$scope.friends
。
答案 2 :(得分:0)
正如@Maximus建议的那样,我在将$scope.reverse
的值切换为true或false之前添加了一个检查。
$scope.sortBy = function(propertyName) {
$scope.propertyName = propertyName;
// check all the values of propertyName i.e. age in the array
for (var i=0; i < friends.length; i++) {
// toggle $scope.reverse only when the values are not same (zero in my case)
if (friends[i].age !== 0) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
}
}
};