Filter objects in AngularJS ng repeat based on one attribute with the help of a text box

Looking for a solution to my current issue where I need to implement a filter on ng-repeat results using a text box. Specifically, I want the filter to target only one particular column when a hashtag is used as the first character in the search term. For instance:

  1. Default behavior: Filter based on text entered in the search box, applying the filter to all attributes of each user.
  2. Filter by a single attribute when a user enters a hashtag followed by a value.

    #ID: 33

    This will filter users with an ID containing '33'.

    #date: 1/12/2014

    This will filter users with the specified date.

var users = [{
  "name": "Bruce",
  "city": "Thailand",
  "date": "1/12/2014",
  "id": 3376848
}, {
  "name": "Frank",
  "city": "Bangladesh",
  "date": "11/10/2014",
  "id": 4482771
}, {
  "name": "Judith",
  "city": "Philippines",
  "date": "13/9/2015",
  "id": 4981921,

}, {
  "name": "Earl",
  "city": "Ukraine",
  "date": "21/6/2015",
  "id": 4024523,
}];

Answer №1

If you want to filter a variable within scope (referred to as "search" in the code below), follow these steps:

When the variable starts with "#", only search on that property. If it doesn't start with "#", search on all properties.

A new array named "filteredUsers" is created to avoid modifying the original "users" array.

To simplify things, utilize Angular's filter service (make sure to include $filter in your controller).

var app = angular.module("app", [])
  .controller("controller", function($scope, $filter) {

    var users = [{
      "name": "Bruce",
      "city": "Thailand",
      "date": "1/12/2014",
      "id": 3376848
    }, {
      "name": "Frank",
      "city": "Bangladesh",
      "date": "11/10/2014",
      "id": 4482771
    }, {
      "name": "Judith",
      "city": "Philippines",
      "date": "13/9/2015",
      "id": 4981921,

    }, {
      "name": "Earl",
      "city": "Ukraine",
      "date": "21/6/2015",
      "id": 4024523,
    }];

    $scope.search = "";
    $scope.filteredUsers = users;

    $scope.$watch("search", function(newVal, oldVal) {

      // if the search value starts with '#'
      if (newVal.substring(0, 1) === "#") {
        var searchProperty = newVal.substring(1, newVal.indexOf(":")); 
        var searchValue = $scope.search.substring(newVal.indexOf(":") + 1).trim(); 

        if (searchProperty && searchValue) {
          var searchObject = {};
          searchObject[searchProperty] = searchValue;
          
          $scope.filteredUsers = $filter('filter')(users, searchObject, false);
        } else {
          $scope.filteredUsers = [];
        }
      } else {
         $scope.filteredUsers = $filter('filter')(users, newVal, false);
      }

    });

  });
pre {
  margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>

<div ng-app="app" ng-controller="controller">

  Search:
  <input type="text" ng-model="search" />


  <h4>User</h4>
  <pre ng-repeat="user in filteredUsers">

    {{user | json}}

  </pre>

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

Utilizing AJAX in Django applications

I'm currently working on integrating a basic AJAX function with Django, but I seem to be facing some issues. The request.is_ajax() function is returning False, and using event.preventDefault() doesn't prevent the form from getting submitted. Her ...

Managing API responses and notifications within a Redux store: tips and best practices

Every time I trigger an action, I want to make sure that the API response is checked before displaying a success message. For example, in the function below where I delete an item using react-redux dispatch: dispatch(deleteItemID(itemId)); notify.show(&quo ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...

An error occurred due to an unexpected identifier, '_classCallCheck', while the import call was expecting exactly one

Encountering an unexpected identifier '_classCallCheck'. Import call requires precisely one argument. Having trouble with React Native. I have attempted every solution found on the internet, but none proved successful. Is there any way to upgrade ...

Guide for sending a JSON object as a parameter from an AngularJS frontend to a WebAPI method and fetching the data

I am facing an issue with passing data from an AngularJS front end to a WebAPI and retrieving another set of data to display on a grid. I have been attempting to pass the data as a JSON object to the WebAPI method, where the parameter being passed is a Cla ...

Converting an array into JSON format in JavaScript without duplicate curly braces

Having two parallel mysql queries in node js is meant to retrieve data more efficiently. The following javascript code reads from a mysql database and stores the results in a javascript object: async.parallel({ aaChannelsCount: function(cb) { /* G ...

Deselect an HTML checkbox using a corresponding label's "for" attribute

Below is the html code I am using to display a checkbox with an image: <div class="testClass"> <input id="111" name="compare_checkbox" type="checkbox" /> <label for="111"> <i class="icon" aria-hidden="true"&g ...

VueJS integrated with FullCalendar: Dynamically load FullCalendar only after linking required scripts in index.html

When trying to incorporate fullCalendar into my Vue component, I encountered the error message "fullCalendar is not a function." It appears that the scripts I have included in my index.html file are loading after the Vue component has already been loaded. ...

Maintaining the 'loggedIn' state across refresh in React

Hello, I am new to React and single page applications in general. I am currently working on making my login state persistent across my application, but I am facing issues when the user refreshes the page. Currently, I have a method in my login form that co ...

Ways to determine if a textbox is empty and trigger a popup notification with jQuery

I'm having trouble with checking if the textbox is empty in my form. Every time I try to submit, instead of receiving an alert message saying "Firstname is empty," I get a message that says "Please fill out filled." ('#submit').click(func ...

Utilizing Vue.js to effectively filter within a nested array

I'm currently facing an issue with filtering a nested array within an array of objects in Vue.js. Take a look at this snippet from my component code: computed: { filteredProducts: function () { // https://codepen.io/arhey/pen/QrbxdX ...

Is it necessary to provide a null argument for optional parameters in JavaScript functions/methods?

Is passing null as an argument necessary for optional parameters? Included below is code from the Mongoose documentation for reference: Model.find(conditions, [projection], [options], [callback]) // Example usage // providing options and executing immed ...

Sending intricate JavaScript object to the controller. The array of objects is consistently empty

I am facing an issue with passing an object to my C# controller. While all the properties are getting populated correctly, the list I have always ends up with a count of 0. I've tried setting the header to content-type/json and using Json.stringify. F ...

Tips for achieving expansion of solely the clicked item and not the whole row

I am trying to create a card that contains a cocktail recipe. The card initially displays just the title, and when you click on a button, it should expand to show the full menu and description. The issue I'm facing is that when I click on one element, ...

Ensure the main checkbox is selected using jQuery

Currently, I am in the process of developing a JavaScript function that will automatically mark a parent checkbox if its child checkbox is checked (only if it's not already marked). For this task, I'm utilizing jQuery. Below is a snippet of my HT ...

Is there a way to trigger Material-UI SpeedDialAction onClick events only when the SpeedDial is open and clicked, not when it is hovered over?

After making a modification to material-ui's <SpeedDial> component by removing the onMouseEnter={handleOpen} prop, I noticed that the onClick event within the <SpeedDialAction> component no longer triggers when clicking on a menu item. It ...

The task "grunt-karma.js" is currently being loaded, but unfortunately an error has occurred: SyntaxError - An unexpected identifier was found

Encountering an issue when loading "grunt-karma.js" tasks while all other tasks are loading correctly. This problem started to occur after updating several dependencies, including grunt-karma and karma. Here is the section from my package.json: "grunt-ka ...

Ways to remove unnecessary div containers in Nuxt js?

This is an example of my page: https://i.sstatic.net/CYCRL.png Showing the Nuxt layout: <template> <div> <Nuxt /> </div> </template> After being compiled by Nuxt, it generates: https://i.sstatic.net/CYdX3.png You ...

How can I activate ng-change using jQuery?

My select tag looks like this: <select ng-change="doSomething()" ng-model="myModel"> </select> Currently, I am using a jQueryUI control (combobox) for my select tag. However, the "change" event triggered from jQuery does not activate the ng-c ...

Eliminating blank or unspecified elements within an array

I'm struggling to remove empty or undefined elements from an array. Here's the code I've tried: function clean(item) { for (var i = 0; i < item.length; i++) { if (item[i] === undefined || item[i] == "") { item.spl ...