Sort objects based on a specific property that they possess

In my current setup, I have an array of objects structured as shown below:

$scope.people = [{name:
                  {last:"Doe", first:"John"}},
                 {name:
                  {last:"Smith", first:"Joe"}}];

My goal is to implement a live filter feature based on last names using a text box.

To see the implementation in action, you can visit this jsfiddle link: http://jsfiddle.net/HB7LU/4287/

Your assistance on this matter would be greatly appreciated. Thank you!

Edit: Apologies for providing the incorrect jsfiddle link initially.

Answer №1

Starting with your fiddle example, I would suggest the following:

HTML

<div ng-controller="MyCtrl">    
  <input ng-model="search" ng-init="search = ''" placeholder="type to search" />
  <div ng-repeat="person in people | filter:{name.last: search}">
    {{ person | json }}
  </div>
</div>

JS

var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
    $scope.people = [{ name: { last: 'Doe', first: 'John' } },
                     { name: { last: 'Smith', first: 'Joe' } }];

}

Check out the plunker demo here

Answer №2

Let's implement a new custom filter!

Expanding on your current code:

myApp.filter("customFilter", function() {
    return function(items, searchTerm) {
        if(!searchTerm) {
            return items;   
        }
        var filteredItems = [];
        for(item in items) {
            if(items[item].name.last.indexOf(searchTerm) == 0) {
                filteredItems.push(items[item]);
            }
        }
        console.log(filteredItems);
        return filteredItems;
    }
});

Now, you can apply this custom filter named "customFilter" anywhere in your HTML. Simply use it like this:

<div ng-controller="MyCtrl">
    <input ng-model="search.name.last"/>
    <div ng-repeat="person in people | customFilter:search.name.last">
        {{person.name.last}}, {{person.name.first}}
    </div>
</div>

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

Steps to set up gapi-script authentication with next-auth in a Next.js application

I have encountered an issue while working on my open-source project that involves utilizing the Google Drive API. Can anyone guide me on how to set up gapi-script authentication using next-auth in a Next.js project? I have managed to implement authentica ...

Shifting the final child to the front position proves unsuccessful with jQuery

I have attempted to move the last element in my list to the first position upon clicking, but unfortunately, it is not working as expected. I followed the advice provided in response to a question on the following page: Move last child to first position. W ...

Tips for leveraging OOP to eliminate redundant code repetition

How can I avoid repeating code when displaying multiple quizzes on the same page? Currently, I have a JavaScript function that duplicates everything for each quiz, with only a few variables changing in the second function. The problem arises when I need t ...

Find the ID of the clicked table row using HTML and JavaScript

Currently, I am trying to implement this code snippet: <td align="center"> <div class="dropdown"> <button onclick="DropdownShow(this)" class="btn btn-default glyphicon glyphicon-picture"></button> <div id="@TableR ...

End-to-end testing in Angular for non-Angular applications

Is it possible to utilize angular e2e tests for testing non-angular applications, or would it be more advantageous to choose selenium webdriver instead? ...

The functionality of Router.push() seems to vary depending on the timing

I'm attempting to utilize router.push() to modify the URL when the Search button is clicked. However, I've encountered a situation where this function only works sporadically. Ideally, after clicking the button, the user should be directed to the ...

What is the process for transferring information from a Ruby controller to an application JavaScript using AJAX?

When clicking a button, an AJAX call is made in my application.js file. It sends 3 data points to the events_controller#check action: //application.js $(document).on('click', "#check-button", function(){ ... $.ajax({ ...

The function of removing the ng-submitted class in AngularJS after form submission seems to be malfunctioning when using setPristine and setUnt

When a form is submitted in Angular, the class ng-submitted is automatically added by default. In my attempts to reset the form state by using $setPrestine and $setUntouched, I encountered some errors that prevented it from working properly. Examples of t ...

Having difficulty linking the Jquery Deferred object with the Jquery 1.9.1 promise

I have been developing a framework that can add validation logic at runtime. This logic can include synchronous, asynchronous, Ajax calls, and timeouts. Below is the JavaScript code snippet: var Module = { Igniter: function (sender) { var getI ...

After the checkbox is clicked, I must send a boolean value to the function through the input flag in AngularJS

<input class="bx--toggle" id="toggle-view" type="checkbox" ng-model="vm.monthView" ng-change="vm.getRelevantData()" ng-attr-data-modal-target="{{vm.alertForSaveAll ? '#add-save-all-alert-modal': 'undefined'}}"> Within this p ...

Utilizing the currentUser object in AngularJS

My current setup in the app.js config consists of the following code for secure routes: var checkLoggedin = function($q, $timeout, $http, $location, $rootScope){ // Create a new promise var deferred = $q.defer(); // Send an AJAX request to check if ...

Obtain the textfield whenever the user desires

I have added an image upload file field in the form. If the user wants a multi-select field, I want to allow the user to choose the number of files they want to upload. Take a look at my text field below: <div class="form-group col-lg-10"> {! ...

What is the best way to sort my API responses to display only users who are either currently online or offline?

Hi everyone, I've made great progress on my project so far without any assistance (pretty proud of myself), but now I could use some help. I'm working on creating a tabbed menu that filters the results of my API calls to display: All users, Onlin ...

Two separate tables displaying unique AJAX JSON response datasets

As a beginner in javascript, I am facing a challenge. I want to fetch JSON responses from 2 separate AJAX requests and create 2 different tables. Currently, I have successfully achieved this for one JSON response and table. In my HTML, I have the followi ...

The context of the selector causes an error to be thrown

Why does jQuery throw an exception when I attempt to select an element with context? The code is as follows: jQuery('b', "DAS<br/><br/><b>ID</b> = 02<br/><b>NAMA DAS</b> = CITARUM<br/><b>LUAS ...

Utilize the synchronization feature of ES6 Promises in Jasmine with the then/catch method

I have an angular controller that needs to be tested. This controller utilizes a service to fetch data from a server, and the service returns ES6 Promises. function MyController($scope, MyService) { $scope.doSomething = function () { MyService.foo() ...

Replicate the action of highlighting a section of a website and copying it to the clipboard using JavaScript

I am currently in the process of transferring an outdated application to a new platform, but I'm facing difficulty understanding the changed JavaScript code. My goal is to find a parent HTML element named "output" and then select all its child elemen ...

How can you retrieve the input value in JavaScript when the cursor is not focused?

Here is an input I am working with: <a-form-item label="user" :colon="false"> <a-input placeholder="user" name="user" @keyup.enter="checkUser"/> </a-form-item> Within my methods: chec ...

Error Handling in Angular2 MVC 4 Project Route Issues

Here is the structure of my Mvc 4 Project with angular 2 implemented: Solution 'Angular2Starter' |-- angular2Starter | `-- Controllers | `-- HomeController.cs |-- src | |-- app | | |-- home | | | |-- home.component.ts | ...

Returning data to be displayed in Jade templates, leveraging Express and Node.js

Yesterday, I had a question. Instead of using next() and passing an Error object, I decided to figure out what it was doing and replicate it. So now, when someone logs in and it fails, I handle it like this: res.render("pages/home", { ...