Skip to content

Commit 778ad1a

Browse files
committed
fix(orderBy): support string predicates containing non-ident characters
The orderBy filter now allows string predicates passed to the orderBy filter to make use property name predicates containing non-ident strings, such as spaces or percent signs, or non-latin characters. This behaviour requires the predicate string to be double-quoted. In markup, this might look like so: ```html <div ng-repeat="item in items | orderBy:'\"Tip %\"'"> ... </div> ``` Or in JS: ```js var sorted = $filter('orderBy')(array, ['"Tip %"', '-"Subtotal $"'], false); ``` Closes angular#6143
1 parent bc42950 commit 778ad1a

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/ng/filter/orderBy.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -62,18 +62,26 @@
6262
*/
6363
orderByFilter.$inject = ['$parse'];
6464
function orderByFilter($parse){
65+
var QUOTED_STRING_REGEXP = /^\s*(['"])([^'"]*)\1\s*$/;
6566
return function(array, sortPredicate, reverseOrder) {
67+
var locals;
6668
if (!isArray(array)) return array;
6769
if (!sortPredicate) return array;
6870
sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
6971
sortPredicate = map(sortPredicate, function(predicate){
70-
var descending = false, get = predicate || identity;
72+
var descending = false, get = predicate || identity, match;
7173
if (isString(predicate)) {
7274
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
7375
descending = predicate.charAt(0) == '-';
7476
predicate = predicate.substring(1);
7577
}
7678
get = $parse(predicate);
79+
if (get.constant) {
80+
var key = get();
81+
return reverseComparator(function(a,b) {
82+
return compare(a[key], b[key]);
83+
}, descending);
84+
}
7785
}
7886
return reverseComparator(function(a,b){
7987
return compare(get(a),get(b));

test/ng/filter/orderBySpec.js

+12
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,16 @@ describe('Filter: orderBy', function() {
3131
toEqual([{a:2, b:1},{a:15, b:1}]);
3232
});
3333

34+
it('should support string predicates with names containing non-identifier characters', function() {
35+
expect(orderBy([{"Tip %": .25}, {"Tip %": .15}, {"Tip %": .40}], '"Tip %"'))
36+
.toEqualData([{"Tip %": .15}, {"Tip %": .25}, {"Tip %": .40}]);
37+
expect(orderBy([{"원": 76000}, {"원": 31000}, {"원": 156000}], '"원"'))
38+
.toEqualData([{"원": 31000}, {"원": 76000}, {"원": 156000}])
39+
});
40+
41+
it('should throw if quoted string predicate is quoted incorrectly', function() {
42+
expect(function() {
43+
return orderBy([{"Tip %": .15}, {"Tip %": .25}, {"Tip %": .40}], '"Tip %\'');
44+
}).toThrow();
45+
});
3446
});

0 commit comments

Comments
 (0)