Reputation: 28803
I'm trying to filter a list of people by the starting letter of their first name in an AngularJS repeater.
The repeater is as follows:
<li ng-repeat="person in people | orderBy: 'firstname' | firstLetter:'firstname':'A'">
<a ui-sref="people.details({ personId: {{person.id}} })">
<span class="list__icon"><img src="img/avatar.png"></span>
<span class="list__text">
<span class="list__text__name">{{person.firstname}} <b>{{person.lastname}}</b></span>
</span>
</a>
</li>
So I order it by first name and then use a custom filter called firstLetter
:
.filter('firstLetter', function () {
return function (input, letter) {
input = input || [];
var out = [];
input.forEach(function (item) {
if (item.charAt(0).toLowerCase() == letter) {
out.push(item);
}
});
return out;
}
});
However I get an error that charAt
isn't a function... Am I passing the parameters to the filter incorrectly?
Upvotes: 1
Views: 4053
Reputation: 2176
Your firstLetter
filter is missing an additional param. The first param input
refers to the array which is being repeated through (in this case, people). The second param, letter
should actually be the third param of your filter declaration.
.filter('firstLetter', function () {
return function (input, key, letter) {
input = input || [];
var out = [];
input.forEach(function (item) {
console.log('item: ', item[key][0].toLowerCase());
console.log('letter: ', letter);
if (item[key][0].toLowerCase() == letter.toLowerCase()) {
out.push(item);
}
});
return out;
}
});;
Upvotes: 2
Reputation: 1095
Yes you are passing parameters to filter incorrectly. By default filter input i.e your array will get passed as a first parameter.
.filter('firstLetter', function () {
return function (objects, input, letter) {
var out = [];
angular.forEach(objects,object){
var item = object[input];
if (item.charAt(0).toLowerCase() == letter.toLowerCase()) {
out.push(object);
}
});
return out;
}
});
Upvotes: 2