AngularJS allows you to easily filter a list of people based on the first letter of their first name

I'm attempting to sort through a group of individuals based on the first letter of their first name within an AngularJS repeater.

Here's how the repeater looks:

<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>

First, I organize it by first name and then apply a personalized 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;
    }
});

Nevertheless, I encounter an error stating that charAt is not a function... Could I be passing the arguments to the filter incorrectly?

Answer №1

It seems like there is a small issue with your firstLetter filter implementation. The second parameter letter should actually be the third parameter in your filter declaration. Currently, it is missing an additional param which is causing some confusion.

.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;
    }
});;

Answer №2

It seems like the parameters are being passed to the filter function incorrectly. By default, the input array will be passed as the 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;
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deactivate rounding numbers in jQuery AJAX

When using jQuery to send numbers, I noticed that the decimals are not saved correctly. For example, 2.5 is saved as 3 and 17.5 is saved as 18. $("#sendnomreform").on('submit',(function(e) { e.preventDefault(); $('#loading').s ...

Utilizing Database Data for Angular Google Maps Polyline Coordinates

My goal is to showcase a Polyline on an Ionic mobile app using Angular Google Maps, utilizing coordinates fetched from a database. After studying the documentation on the Angular Google Maps website on acquiring coordinates and trying to generate a path wi ...

Obtain an item from an array by utilizing the property with Lodash _.find

I currently have an array of objects called memberToChange.checkboxes: ICheckbox[] structured like this: https://i.stack.imgur.com/LyKVv.png Within this setup, there is also a variable named internalNumber with the value "3419". My objective is to locate ...

JavaScript's power lies in its ability to create dynamic regular expressions

Currently, I am working on code that requires matching a specific number of digits after a decimal point. Here is what I have so far: var input = getValueFromUser(); var count = getCount(); var x = Number(input.toString().match(/^\d+(?:\.\d ...

Monitoring modifications to nested information in Vue.js

I am looking to monitor changes in the 'families' variable, which contains nested objects. <component-test v-for="family of familiesToDisplay" // rest /> data: () => ({ families: [], }), computed: { ...

Angular.js ng-repeat directive with an if statement

I've been working on implementing an if statement into a ng-repeat directive, but I'm struggling a bit. Here's the code that is currently working for me: <p ng-repeat="list in lists">{{list[id].title}}</p> What I'm trying ...

Identify the Google Maps Marker currently displayed on the screen

Is there a way to generate a list of markers within the zoom range for Google Maps, similar to the functionality on this site I'm curious if I can achieve this using jQuery or if there is a built-in function for Google Maps v3? Thank you! ...

Utilize Angular filters for manipulating UI-Router URL parameters

Exploring options to filter URL parameters. For instance: ui-sref="stateName({slug:{{someobj.slug | someFilter}}})" What would be the best way to implement this? ...

Is there a way to trigger an animation after the completion of ng-repeat binding?

Check out this plunker that demonstrates an interesting behavior: the class ng-hide is removed from a tag before ng-repeat has finished creating the HTML view of the data. This results in the height of the element not being final when removeClass is trigge ...

NG0303: Unable to establish a connection with 'ngbTooltip' as it is not recognized as a valid property of 'button'

ERROR: 'NG0303: Can't bind to 'ngbTooltip' since it isn't a known property of 'button'.' Encountering this issue in my Angular 12 project when running local tests, the ngbTooltip error is present in all .spec files. ...

What is the best way to convert my query for use with MongoDB in a Node.js application?

Here is the structure of my MongoDB query: db.test.findOne({"User.David":{$elemMatch:{"action":"todo","status":"Done"}}}) I am currently developing a node.js API that allows users to retrieve documents based on username and status. Below is my attempt a ...

Utilizing JQuery and Jade to extract and display information from a Node.js server

I am currently working with the Jade framework for frontend and using Node.js & express for backend development. When rendering a view with data, I am encountering an issue where I can't access this data using JQuery. Below is my service in Node.js ...

The isolated scope member is being updated within the link/controller function, but it becomes undefined when passed to the controller

In the code snippet below: HTML: <body ng-controller="MainCtrl"> <main-dir data="data" on-update-map="updateMap(datalength)"></main-dir> </body> JS: app.directive('mainDir', function () { function DatasetDirect ...

The header in the fetch() function is displaying as application/x-www-form-urlencoded rather than the expected application/json

Update #2: The issue has been resolved, you can find the solution in my own answer (which I am unable to accept at this time). I have a React application running on Heroku with a node.js backend via Express. In the frontend, I am attempting to send a POST ...

Which is better: Utilizing Ajax page echo or background Ajax/direct HTML manipulation?

I am facing a dilemma and I could really use some guidance. Currently, I am in the process of developing an ordering system using PHP/Smarty/HTML/jQuery. The main functionality revolves around allowing sellers to confirm orders on the site. My goal is to ...

Alter the uploaded picture and subsequently send the revised image through an HTML form

Currently, I am working on an HTML form that includes a file input for accepting images. My goal is to take the uploaded image from the user and make some modifications using JavaScript before submitting the modified version instead of the original one. I ...

Ways to resolve the issue "Module Not Found Error: Cannot locate module './src/bot/index'"

Whenever I run the command node src/index.js I encounter the following error message: Error: Cannot find module './src/bot/index' Require stack: C:\Users\MIMAR\Desktop\EJS\src\index.js What could be causing this er ...

Pass along the value of a link upon clicking on it

I have implemented a simple list using md-data-table: <tr md-row md-select="device" md-on-select="logItem" md-auto-select="options.autoSelect" ng-repeat="device in devices.data"> <td md-cell style='text-align:left;vertical-align:middle&apo ...

Tips for adjusting the height of MUI Date Picker to fit your preferences

<Box sx={{ m: 1 }}> <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker label="Enter Date" slotProps={{ textField: { height: "10px" } }} ...

Adjusting the transparency of numerous elements using JavaScript or jQuery

My task involves creating a large form where elements initially have an opacity of 0.5, and when a button is clicked, the opacity changes to 1.0. While I can achieve this using JavaScript, I want to find a more efficient way by avoiding individual if state ...