Angular allows for filtering and separating variables

Here is the code snippet that I am working with:

<input ng-model="search" type="text">

<td ng-repeat="key in targets">
    {{ display_names[key] }}
</td>

To clarify further:

  • targets contains IDs like key012

  • display_names is an object with keys such as key012: "USA"


I want to filter the values in display_names based on the search input. While I know how to filter key using AngularJS documentation, I am still figuring out how to filter display_names.


Example

Here's a complete example:

 var TS = angular.module('myapp', []);
 
 TS.controller('test', function($scope) {
   $scope.targets = ["id_1", "id_2"];
   $scope.display_names = {
     "id_1": "USA",
     "id_2": "Mexico"
   };
 });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myapp" ng-controller="test">
  <input ng-model="search" placeholder="Search...">

  <ul>
    <li ng-repeat="key in targets">{{display_names[key]}}</li>
  </ul>
</body>

Answer №1

<td ng-repeat="key in targets">
    <span ng-if="display_names[key].indexOf(search) > -1">{{ display_names[key] }}</span>
</td>

Consider using ng-if, or you have the option to use ng-show. Learn about their differences here

This will trigger a refresh of the values in the ng-repeat as you type in the search input, which should be bound to $scope.search

If you need to perform a case-insensitive search, remember to use the toLowerCase() function before calling indexOf

display_names[key].toLowerCase().indexOf(search) > -1

Answer №2

If you can't use a filter | in the HTML because the value you want to filter against is not present in the array you are iterating over, consider using ng-if to show/hide elements based on the search criteria. Here's an example:

<div ng-repeat="key in targets" ng-if="!search || !!display_names[key].match(search)">
  {{ display_names[key] }}
</div>

The double negation (!!) boolean cast is used to avoid triggering unnecessary digest cycles when matching with Regex objects.

It's also recommended to iterate over <tr> instead of <td>, and ensure that these elements are enclosed within a <table>.

For more examples, check out this link: http://plnkr.co/edit/qrpLKD9x4IBXowpIgnrf?p=preview


An alternative approach would be to create a custom filter, although it requires more effort:

.filter('displayNames' function () {
  return function (key, names, search) {
    return !search || !!names[key].match(search);
  };
});

This custom filter can then be used like so:

key in targets | displayNames:display_names:search

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

showing elements within an array

I have created a JavaScript array in the following way: var chosenColors= { 'Orange' : $("#Orange").val(), 'Light Blue' : $("#LightBlue").val(), 'Dark Red' : $("#DarkRed").val ...

Create a modal window that displays dynamic content and updates the URL accordingly

Is it possible to create a modal window that opens up different routing, similar to the functionality seen on this website: ...

Simple Method to Retrieve JSON Data from a Data Attribute Using .attr() (or Similar Function)

It seems like I'm hitting a roadblock with something fairly basic, and I can't seem to find a solution. I've got a JSON array that I want to pass to my JavaScript using a data attribute on a div like this: <div id="scope" data-json=&apo ...

A guide on updating data with duplicate values in Knex

Suppose I have the following array of data: const customerIds = [ '7d8206d2-74bc-4b90-a237-37f92486cde4', 'e594fe7f-d529-4a2f-ab24-ffc4e102268c', '7d8206d2-74bc-4b90-a237-37f92486cde4' ] As seen, there are duplicate IDs ...

Incorporate tinyMCE into a colorbox module

Currently, I am facing an issue on my website where there are textareas with tinymce. While I can view all the textareas correctly, when trying to open colorbox within a textarea, it does not inherit the tinymce properties. The code snippet used to open co ...

qooxdoo modal dialogue box and the transparency of surrounding widgets

Currently working on coding using qooxdoo and I've encountered an issue with a TabView on the root. The TabView has a Dock layout and I have added a window with the modal property set to true. Upon opening the window, I've noticed that the widge ...

Running into issues on Heroku with Node, Gulp, and Browserify: Module Not Found Error

My asset building process relies on Gulp. Specifically for Javascript, I have a task set up with Browserify to handle all code dependencies. While everything runs smoothly locally, deploying to Heroku results in a Gulp failure with the following error: 2 ...

Error in Vue.js: "Trying to access properties of an object that is undefined (specifically '$refs')"

When we trigger methods from a parent component in a child component, we use the following code: await this.$refs.patientinputmask.$refs.patientpersonaldata.ChangePersonalData(); await this.$refs.patientinputmask.$refs.patientaddressdata.SavePersonalAddres ...

What could be causing jQuery.css() to not function properly?

I've been encountering some challenges with a piece of code and haven't been able to make it function as intended. I'm relatively new to JavaScript/jQuery, so bear with me as I navigate through this learning process. As part of the Free Cod ...

Removing an unnamed cookie

A mysterious cookie mysteriously appeared on my website, courtesy of Sharethis (value "sharethis_cookie_test"). This cookie is causing all sorts of session issues for me specifically on Chrome. Despite removing the sharethis plugin from my site, this pesky ...

Can you change styles with radio buttons in JavaScript without using JQuery?

I am struggling with an error message "Uncaught Type Error: Cannot set property 'onchange' of null" while trying to implement three radio buttons that are supposed to change font size. Each button is assigned an id for the respective font size it ...

What is the reason for the initial display of an empty option when using AngularJS to select an

Every time I refresh the page, the initial option is blank. How can I set Any Make as the default selection? Below is the code snippet from my view: <select class="form-control" id="make" name="make" ng-init="Any Make" ng-model="makeSelected" ng-chan ...

The gadget is displaying as "undefined"

I am working on a project that involves mapping devices based on the videoinput. I am trying to display the values, but it seems that the device is showing as not defined. Can anyone help me figure out what mistake I might be making here? Thank you in ad ...

Ways to showcase HTML content in angular when receiving entities

Is there a way to properly display HTML characters using HTML entities? Take this scenario for example: Let's say we have the following string: $scope.myString = "&lt;analysis mode=&quot;baseball&quot; ftype=&quot;&quot; version ...

extract the chosen option from the dropdown menu using AngularJS and input it into a text field

Hello! I am a beginner in AngularJS and currently working on creating a unit converter demo app. My app consists of two dropdowns for selecting the source and destination units. I need help in getting the selected values from the dropdowns into an input fi ...

Set the array back to its initial value of 1 using jQuery and

After making substantial edits to this question, I find myself in need of a reset button for the code. The current item needs to be reset back to 1 so that I can use it again, but the issue lies in the fact that only the current item is reset while the hig ...

Storing a link's id in JavaScript - the essential guide

Currently, I am exploring ways to utilize the selenium IDE in order to retrieve, save, and apply the ID of a specific record. The HTML code in question is as follows: <span class='small'><a href="/users/change_district/31">(Select)& ...

A new error has been thrown due to an input error. The error message indicates that the input

I am facing an issue with my Redux store code. It throws an input type error or input invalid error in development mode, but strangely not in production. I am unsure why this is happening and need some help. import { createStore, applyMiddleware, combine ...

Issue: [ng:areq] The function 'DepartmentCustomReportController' is missing and undefined in Internet Explorer

I am encountering an issue specifically in Internet Explorer, as the same controller works without any problems in Chrome. Here is a snippet of my index.html file: <script src="assets/js/boostrapJs/jquery-1.11.1.min.js"></script> <script s ...

Passing an Array from JQuery to PHP using AJAX

Although there have been numerous inquiries on this topic, I am still struggling to grasp the concept. Here is the JS code in question: function ClickToSave() { var data1 = CKEDITOR.instances.textToBeSaved1.getData(); var data2 = CKEDITOR.instances.textTo ...