AngularJS and orderby in ng-repeat with special characters - angularjs

I am having trouble ordering strings containing characters that are not in the English alphabet ( š,č,ž,..)
Here is the fiddle: http://fiddle.jshell.net/vhhgh/
The letters are from the Slovenian alphabet.

It's been a while, but I found other solution: fiddle
HTML:
<div ng-app='test'>
<h2>Users</h2>
<div ng-controller="UsersCtrl">
<ul>
<li ng-repeat="user in users | localeCompareString">
{{user.surname}} {{user.name}}
</li>
</ul>
</div>
</div>
JS:
(function(angular) {
'use strict';
var test=angular.module('test',[])
.controller('UsersCtrl', ['$scope',function($scope) {
$scope.users = [
{name:'Ben', surname:'Živkovič'},
{name:'Ken', surname:'AlGore'},
{name:'Erica', surname:'Červ'},
{name:'Jane', surname:'Šinigoj'},
{name:'Kevin', surname:'Sort'},
{name:'Roger', surname:'Willson'},
{name:'Kim', surname:'Zorro'}
];
}]).filter('localeCompareString',function(){
return function (items) {
//window.console.log(items);
items.sort(function (a, b) {
return a.surname.localeCompare(b.surname);
});
return items;
};
});
})(window.angular);

Ordering arrays of strings with "foreign" letters isn't as easy to do as you might think. Actally, it can be a right pain in the ... to get right. The problem boils down to the fact that the Unicode charset contains (pretty much) all charactrers in existance, so a universal lexicographical sorting isn't possible since different countries all have different ways they expect the sorting to be handled.
To get around this, I've found TCollator, a small library aiming at fixing that issue, very useful.

You can compare two strings with the String.localeCompare() method. It's then easy to create your own filter to sort your array:
MyApp.filter('myOrderBy', function () {
return function (array, property, reverse) {
var result = array.sort(function (object1, object2) {
if (angular.isUndefined(property)) {
return object1.localeCompare(object2);
}
return object1[property].localeCompare(object2[property]);
});
return reverse ? result.reverse() : result;
};
});

Starting from AngularJS 1.5.7, orderBy takes an optional comparator function. The docs contain an example involving a locale-sensitive comparator.

Related

Strip characters from ng-repeat filter?

I'm writing an Angular app that will read a magnetic stripe card from a USB device. When I swipe a test card, I get a string back containing the card number. For example, ;12345?, where 12345 is the card number.
The data my app uses doesn't include these "control characters", so I'd like to strip them out of the search string if the string starts with a ; and ends with a ?.
When I write a custom filter:
angular.module('app.filters', [])
.filter('stripcardcontrolcharacters', function() {
return function(text) {
if(text.substring(0, 1) === ";" && text.substring(text.length - 1) === "?") {
return text.substring(1, text.length - 1);
}
};
});
It fails because I'm ng-repeating over an array, and not the string that I've searched for.
How would I get what string I'm filtering for and strip the characters from it?
EDIT: Current suggestion is to use a filter to modify the array to ADD in the control characters so filter: can find it. I might go with that for now, but I'm still curious to know if you can write such a filter
You're passing the entire array to your filter via
ng-repeat="user in users | stripcardcontrolcharacters ...
If that's how you want it to work, you would need to treat it as an array, for example
return function(textArray) {
var invalidChars = /\D/g; // just an example
return textArray.map(text => {
console.log(text);
return text.replace(invalidChars, '');
});
}
You are probably applying the filter to the array, not the string itself.
Look at this example:
angular.module('test', [])
.controller('testController', function($scope){
$scope.names = ['John Doe', 'Jane Doe'];
})
// The test filter
.filter('strip', function(){
return function(str) {
return str.substring(1, str.length - 1);
};
});
And here is how to use it:
<body ng-app="test" ng-controller="testController">
<p ng-repeat="name in names">
{{name | strip }}
</p>
</body>
Note that I'm applying the filter where I use the value, not in the ng-repeat statement.
And here is the working plunker

Sorting minus number strings with AngularJS 'orderBy'

I am reverse ordering some number strings with the orderBy directive that can be used in conjunction with ngRepeat.
<div ng-repeat="item in standings| orderBy:['-points', '-gd', 'team_name']">
<p>{{item.gd}}
</div>
So it is ordering (in order of priority) 'points', then 'gd' (goal difference), then 'team_name' (alphabetically).
The gd value correctly orders by descending value. The problem I have is with negative number values. In this instance, numbers are returned as strings, and the orderBy function doesn't understand "-2" as being less than "-1", but the opposite.
How can I get ng-repeat to parse the number values into integers, particularly to solve this ordering issue with minus numbers?
I considered making a filter, e.g: {{item.gd | *filterHere* }}, but this wouldn't be seen by the initial ng-repeat directive, which needs to take the source value as an integer.
Any help would be appreciated.
UPDATE:
I tried this filter, but when I call it in my ng-repeat, it returns nothing:
app.filter('stringToInteger', function() {
return function(input) {
angular.forEach(input, function(value) {
parseInt(value.gd);
})
};
return input;
});
In the View:
<p ng-repeat="item in standings | orderBy: '-gd' | stringToInteger">GD = {{item.gd}}</p>
the filter should be like this.
app.filter('stringToInteger', function() {
return function(input) {
angular.forEach(input, function(value) {
value.gd = parseInt(value.gd);
})
return input;
};
});
Use it like this .
<tr ng-repeat="team in teams | stringToInteger | orderBy:'-gd'">
Plunker link for more reference.
https://plnkr.co/edit/GRfMJnRdT1Gu5RXO9elA?p=preview

Adding filter to ng-repeat

I'm currently making a front-end with Angular.
I have a JSON file like following:
{
"groups": [
group1: {
"part":1
},
group2: {
"part":2
}
]
}
And I have lists like following:
<li ng-class="{active: section >= {{group.number}}}" ng-bind="group.title" ng-repeat="group in groups" ></li>
Let's say there are 100 groups in my JSON file. If I want to only show groups with "part":1, how do I add this filter in ng-repeat?
You can pass an object to filter with the key/value you want to filter on:
ng-repeat="group in groups | filter:{part:1}"
try this
ng-repeat="group in groups | filter:{'part': 1}:true"
from official documentation
In HTML Template Binding
{{ filter_expression | filter : expression :
comparator}}
for comparator value if its true
true: A shorthand for function(actual, expected) { return
angular.equals(actual, expected)}. This is essentially strict
comparison of expected and actual.
this gives you the exact match
Consider also passing a function rather than Object into filter (which may work this time, but not all things are easily expressible in a readable fashion directly in the view):
ng-repeat="group in groups | filter:functionOnScope"
The | pipe operates on the thing to the left groups, so filter is a function whose first argument receives groups and whose subsequent arguments appear after the :. You could visualize a | b:c:d | e as e(b(a,c,d)) - once I realized that I used filters more for simple things.
So the second argument filter receives is a predicate (function that takes in something and returns true or false to operate on each element - like a SQL WHERE clause) inside groups. Filters are super useful - if you have quick logic or transformations you want to do in the view (and you don't need to test it) then they can make your controllers and directives more succinct. (So instead of ng-if="collection[collection.length - 1].length > 0" you could write ng-if="collection | last | some", which is much more readable.)
If you have complicated logic, it may be better to put in a controller or directive instead of the view (this is also easier to unit test that way if you care about it) - if it's in the view you need something like PhantomJS at a minimum to emulate the DOM. Assuming you bound some dynamicallySelectedPart on the $scope to 1, 2, etc. maybe as an ng-model on a <select /> so the user can select it, then you can just write this to keep it dynamically up-to-date.
$scope.functionOnScope = function (elementInGroups) {
// Maybe do a check like:
// if ($scope.dynamicallySelectedPart === elementInGroups.part) {
return true;
// }
// Some other logic...
return false;
};
Your JSON looks malformed in that you have an array with key-value pairs.
Below is some code that should work. I am using the Controller ViewAs syntax.
HTML
<div ng-app="MyApp">
<div ng-controller="MyController as me">
{{me.greeting}}
<ul>
<li ng-repeat="group in me.groups | filter:{'part': 1}:true">
{{group}}
</li>
</ul>
</div>
JS
var myApp = angular.module('MyApp',[]);
myApp.controller('MyController', function() {
this.greeting = 'Hola!';
this.groups = [ {id: 'group1', "part":1 }, {id: 'group2', "part":2 } ];
});
Code Pen Here

Angular nested ng-repeat filter items matching parent value

I am passing in 2 arrays to my view. I would like my nested loop to only display where it's parent_id value matches the parent.id. Eg.
arr1 = {"0":{"id":326,"parent_id":0,"title":"Mellow Mushroom voucher","full_name":"Patrick","message":"The voucher says $10 Voucher; some wording on the printout says, \"This voucher is valid for $20 Pizza\" but my purchase price or amount paid also says $20. Shouldn't that be $10","type":"Deals"}};
arr2 = {"0":{"id":327,"parent_id":326,"title":"Re: Mellow Mushroom voucher","full_name":"Patrick Williams","message":"Some message here","type":null};
...
<div data-ng-repeat = "parent in arr1">
<span>{{parent.title}}<span>
<div data-ng-repeat="child in arr2 | only-show-where-child.parent_id == parent.id">
<li>{{child.body}}</li>
</div>
</div>
Is this possible/best practice in angular of should I be filtering the object in node before passing it into angular? Thank you!
There are a couple of ways you could do it... You could create a function to return just the children:
$scope.getChildren = function(parent) {
var children = [];
for (var i = 0; i < arr2.length; i++) {
if (arr2[i].parent_id == parent.id) {
children.push(arr2[i]);
}
}
return children;
};
html:
<div ng-repeat="child in getChildren(parent)">
You could define a filter to do the same thing:
myApp.filter('children', function() {
return function(input, parent) {
var children = [];
for (var i = 0; i < input.length; i++) {
if (input[i].parent_id == parent.id) {
children.push(input[i]);
}
}
return children;
};
});
html:
<div ng-repeat="child in arr2|children:parent">
Both of those methods will execute every digest cycle though. If you have a large list of elements you would definitely want to improve performance. I think the best way would be to pre-process those results when you get them, adding a children array to each object in arr1 with only its children (here using array.filter instead of for loop and array.forEach):
arr1.forEach(function(parent) {
parent.children = arr2.filter(function(value) {
return value.parent_id === parent.id;
};
});
Then in the html you are already working with the parent so you can repeat over its children property:
<div ng-repeat="child in parent.children">
Instead of using filters, data-ng-if can achieve the same result.
<div data-ng-repeat="parent in arr1">
<span>{{parent.title}}<span>
<div data-ng-repeat="child in arr2" data-ng-if="child.parent_id == parent.id">
<li>{{child.body}}</li>
</div>
</div>
The solution depends on how often arrays are changed and how big arrays are.
The fist solution is to use filter. But in this case it would be called at least twice (to make sure that result is "stabilized" - selected same elements).
Other solution is to $watch by yourself original array and prepare "view" version of it injecting children there. Personally I would prefer the second as more explicit.
However if you can reuse "find-the0child" filter in other parts of your application you can go with first one - AngularJS will re-run filter only after original array modified.
If needed I can provide here an example of implementation of one of these options - add the comment to answer.

Custom sort function in ng-repeat

I have a set of tiles that display a certain number depending on which option is selected by the user. I would now like to implement a sort by whatever number is shown.
The code below shows how I've implemented it (by gettting/setting a value in the parent cards scope). Now, because the orderBy function takes a string, I tried to set a variable in the card scope called curOptionValue and sort by that, but it doesn't seem to work.
So the question becomes, how to I create a custom sort function?
<div ng-controller="aggViewport" >
<div class="btn-group" >
<button ng-click="setOption(opt.name)" ng-repeat="opt in optList" class="btn active">{{opt.name}}</button>
</div>
<div id="container" iso-grid width="500px" height="500px">
<div ng-repeat="card in cards" class="item {{card.class}}" ng-controller="aggCardController">
<table width="100%">
<tr>
<td align="center">
<h4>{{card.name}}</h4>
</td>
</tr>
<tr>
<td align="center"><h2>{{getOption()}}</h2></td>
</tr>
</table>
</div>
</div>
and controller :
module.controller('aggViewport',['$scope','$location',function($scope,$location) {
$scope.cards = [
{name: card1, values: {opt1: 9, opt2: 10}},
{name: card1, values: {opt1: 9, opt2: 10}}
];
$scope.option = "opt1";
$scope.setOption = function(val){
$scope.option = val;
}
}]);
module.controller('aggCardController',['$scope',function($scope){
$scope.getOption = function(){
return $scope.card.values[$scope.option];
}
}]);
Actually the orderBy filter can take as a parameter not only a string but also a function. From the orderBy documentation: https://docs.angularjs.org/api/ng/filter/orderBy):
function: Getter function. The result of this function will be sorted
using the <, =, > operator.
So, you could write your own function. For example, if you would like to compare cards based on a sum of opt1 and opt2 (I'm making this up, the point is that you can have any arbitrary function) you would write in your controller:
$scope.myValueFunction = function(card) {
return card.values.opt1 + card.values.opt2;
};
and then, in your template:
ng-repeat="card in cards | orderBy:myValueFunction"
Here is the working jsFiddle
The other thing worth noting is that orderBy is just one example of AngularJS filters so if you need a very specific ordering behaviour you could write your own filter (although orderBy should be enough for most uses cases).
The accepted solution only works on arrays, but not objects or associative arrays. Unfortunately, since Angular depends on the JavaScript implementation of array enumeration, the order of object properties cannot be consistently controlled. Some browsers may iterate through object properties lexicographically, but this cannot be guaranteed.
e.g. Given the following assignment:
$scope.cards = {
"card2": {
values: {
opt1: 9,
opt2: 12
}
},
"card1": {
values: {
opt1: 9,
opt2: 11
}
}
};
and the directive <ul ng-repeat="(key, card) in cards | orderBy:myValueFunction">, ng-repeat may iterate over "card1" prior to "card2", regardless of sort order.
To workaround this, we can create a custom filter to convert the object to an array, and then apply a custom sort function before returning the collection.
myApp.filter('orderByValue', function () {
// custom value function for sorting
function myValueFunction(card) {
return card.values.opt1 + card.values.opt2;
}
return function (obj) {
var array = [];
Object.keys(obj).forEach(function (key) {
// inject key into each object so we can refer to it from the template
obj[key].name = key;
array.push(obj[key]);
});
// apply a custom sorting function
array.sort(function (a, b) {
return myValueFunction(b) - myValueFunction(a);
});
return array;
};
});
We cannot iterate over (key, value) pairings in conjunction with custom filters (since the keys for arrays are numerical indexes), so the template should be updated to reference the injected key names.
<ul ng-repeat="card in cards | orderByValue">
<li>{{card.name}} {{value(card)}}</li>
</ul>
Here is a working fiddle utilizing a custom filter on an associative array: http://jsfiddle.net/av1mLpqx/1/
Reference: https://github.com/angular/angular.js/issues/1286#issuecomment-22193332
The following link explains filters in Angular extremely well. It shows how it is possible to define custom sort logic within an ng-repeat.
http://toddmotto.com/everything-about-custom-filters-in-angular-js
For sorting object with properties, this is the code I have used:
(Note that this sort is the standard JavaScript sort method and not specific to angular) Column Name is the name of the property on which sorting is to be performed.
self.myArray.sort(function(itemA, itemB) {
if (self.sortOrder === "ASC") {
return itemA[columnName] > itemB[columnName];
} else {
return itemA[columnName] < itemB[columnName];
}
});
To include the direction along with the orderBy function:
ng-repeat="card in cards | orderBy:myOrderbyFunction():defaultSortDirection"
where
defaultSortDirection = 0; // 0 = Ascending, 1 = Descending

Resources