Skip to content

Commit

Permalink
fix(orderBy): support string predicates containing non-ident characters
Browse files Browse the repository at this point in the history
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
  • Loading branch information
caitp committed Feb 6, 2014
1 parent a8c1d9c commit 76fe2ba
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/ng/filter/orderBy.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,17 +62,30 @@
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse){
var QUOTED_STRING_REGEXP = /^\s*(['"])([^'"]*)(['"])\s*$/;
return function(array, sortPredicate, reverseOrder) {
var locals;
if (!isArray(array)) return array;
if (!sortPredicate) return array;
sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
sortPredicate = map(sortPredicate, function(predicate){
var descending = false, get = predicate || identity;
var descending = false, get = predicate || identity, match;
if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
descending = predicate.charAt(0) == '-';
predicate = predicate.substring(1);
}
if ((match = predicate.match(QUOTED_STRING_REGEXP)) && match[1] === match[3]) {
// If the predicate is a quoted string, it might contain special characters, and requires
// a different getter expression to work correctly.
locals = locals || {item: null};
get = $parse('item["'+match[2]+'"]');
return reverseComparator(function(a,b) {
locals.item = a, a = get(a, locals), locals.item = b, b = get(b, locals);
return compare(a, b);
}, descending);
}

get = $parse(predicate);
}
return reverseComparator(function(a,b){
Expand Down
6 changes: 6 additions & 0 deletions test/ng/filter/orderBySpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,10 @@ describe('Filter: orderBy', function() {
toEqual([{a:2, b:1},{a:15, b:1}]);
});

it('should support string predicates with names containing non-identifier characters', function() {
expect(orderBy([{"Tip %": .25}, {"Tip %": .15}, {"Tip %": .40}], '"Tip %"'))
.toEqualData([{"Tip %": .15}, {"Tip %": .25}, {"Tip %": .40}]);
expect(orderBy([{"원": 76000}, {"원": 31000}, {"원": 156000}], '"원"'))
.toEqualData([{"원": 31000}, {"원": 76000}, {"원": 156000}])
});
});

0 comments on commit 76fe2ba

Please sign in to comment.