Enhance filtering capabilities in ng-repeat by adding controls

After utilizing ng-repeat to display some JSON data, I have incorporated form controls to filter output data from another JSON file.

Here is a simplified example:

First JSON data:


    var technologies = [
      {"id":"5", "slug":"mysql", "label":"MySQL", "category":"database"},
      {"id":"4", "slug":"html", "label":"HTML", "category":"markup"}
    ]
  

Output:

<ul>
    <li ng-repeat="tech in technologies">
      <span>{{tech.label}}</span> 
      <span><label>required expertise 
        <select>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
        </select></label>
      </span>
    </li>
  </ul>
  

(The filtered technologies are based on user choices made on a previous page.)

The second JSON includes the 'expertise' property that will be used for filtering:


    var people = [
    {
      'label': 'MySQL',
      'slug': 'mysql',
      'talents':[
        {
          'name': 'Stanislav Lem',
          'expertise': 5,
          'desire': 0,
          'last_used': '2009-01'
        },
        {
          'name': 'Ijon Tichy',
          'expertise': 1,
          'desire': 5,
          'last_used': '2011-06'
        }
      ]
    },  ...
    ]
  

This data is currently displayed as follows:

<ul>
    <li ng-repeat="item in people">
      {{item.label}}<br>
      <ul>
        <li ng-repeat="person in item.talents">{{person.name}} &middot; Expertise: {{person.expertise}}</li>
      </ul>
    </li>
  </ul>
  

I am seeking a filter that can utilize the options from the first output to filter the second output. For instance, if MySQL's required expertise is set to '2', only Stanislav Lem should be displayed. I also plan to implement a 'no results found' message if there are no matches for expertise levels.

Check out the Plunker sample here: http://plnkr.co/edit/B0aQp9aCJ2g4OM6fZ3qe?p=preview

Answer №1

Here is a functioning Plunker example: http://plnkr.co/edit/jcb6SfKVPkwt7FFCZFHX?p=preview

To start, make sure to include an ng-model attribute in the select element. I've set this as a property of the technology for easy access.

<select ng-model="tech.required">

I've also added two new functions in your controller to assist in filtering the second list:

$scope.getFilterForSlug = function(slug) {
    var technology = getTechBySlug(slug);

    return function(person) {
        return person.expertise >= (technology.required || 0);
    };
};

function getTechBySlug(slug) {
    return _.find($scope.technologies, {
        slug: slug
    });
}

In the getTechBySlug function, I'm using lodash to retrieve the correct technology object based on the slug. The getFilterForSlug function then generates a filter that compares a person's expertise with the desired level from the select. If no option is selected, the desired level defaults to 0.

Finally, in the HTML section, I made the following additions:

<ul>
    <li ng-repeat="person in filteredPeople = (item.talents | filter: getFilterForSlug(item.slug))">{{person.name}} · Expertise: {{person.expertise}}</li>
</ul>
<span ng-if='!filteredPeople.length'>No Results!</span>

This code creates a filter based on the current slug and applies it to the list of people. The results are stored in the variable filteredPeople, which is used in the span to display a message when there are no matching results.

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 JSON to Fetch User Input in MVC 3

Currently, I am a beginner in ASP .NET MVC 3 and working on my final year project using it. I would appreciate assistance with the following: I want to send data that the user enters in multiple rows as JSON to the controller for processing, and then rece ...

The method of inserting a JSON dates object to deactivate specific days

I am currently utilizing a date picker component that can be found at the following link: While attempting to use the disabledDays section below, I have encountered an issue where I am unable to apply all three options. The blockedDatesData option works o ...

Looking to add a dynamic divider between two columns that can be adjusted in width by moving the mouse left and right?

If you're looking for an example of two columns adjusting their width based on mouse movement, check out this page from W3Schools. I'm trying to implement this feature in my React app, but I'm unsure of how to proceed. Below is the JSX code ...

Analyzing JavaScript performance without causing your browser to crash

I recently experimented with profiling code and found that the most convenient method, at least on Firefox, was to utilize either console's time/timeEnd functions or profile/profileEnd methods, so I gave both a try. The issue I encountered was the li ...

Transmitting a key-value pair data object to the server-side code-behind aspect

Transferring a key value pair object to the server side codebehind. What is the method to send it from JavaScript? And how can it be received in C# codebehind? Modification 1 <script type="text/javascript"> function ABC() { va ...

Using NodeJS and Express: redirection fails to load the specified endpoint

My current project involves a simple e-commerce web application running on localhost built with nodejs and express. Admins are required to register in order to gain access to functionalities such as adding, editing, and removing products from the product l ...

AngularJS event listener fired twice

Currently, I am facing a scenario where one controller is sending out the event, while another controller is set up to listen for it. The code looks like this: In controller A, there is a method defined as follows: $scope.process = function () { var t ...

What is the method for configuring my bot to forward all logs to a specific channel?

const logsChannel = message.guild.channels.cache.find(channel => channel.name === 'logs'); I am looking to set up my bot to send log messages for various events, like member join/leave or message deletion, specifically in a channel named &apo ...

Is a UI routing race problem a concern?

After some observation, I've identified a potential race condition that occurs when switching between states too quickly. For example, let's say I navigate to state A. The directives linked to this state are compiled. This process could take lon ...

Setting up PHP configuration on an HTTP server

I am currently working on a project that requires using a server to host files on the internet. I have limited knowledge of web hosting technologies, but I came across an angular tutorial that utilized a simple server called http-server. Following this tut ...

Utilize Gson to parse a JSON file

Is there a way to access and parse a JSON file stored in the raw folder using Gson? Specifically, I have a method that retrieves SSID strings for the strongest WiFi access points and I want to be able to retrieve the route_number associated with a particul ...

Using Alamofire in Swift to securely parse and handle JSON data

I encountered an issue while working with swift Alamofire. I need to send data to the server in escaped JSON string format, like this: {\"status\":1,\"id\":\"1bcc3331b09d32f7439ad9d5f2acfb35\",\"progress\":[{\" ...

When using jQuery to focus on an input element, the cursor fails to show up

Looking to enhance user experience by focusing on an input element upon clicking a specific div. The HTML structure being used is as follows: <div class="placeholder_input"> <input type="text" id="username" maxlength="100" /> <div ...

How to dynamically change the border-top color of an <a> tag in a menu using a jQuery loop

I am interested in adding a colorful border-top to my menu using jQuery. I know this can be achieved with HTML by including style="border-top-color: red;", but I want to explore the jQuery method. Here is what I have attempted so far: var colors = [ ...

I'm not sure how I can retrieve the pollId from a ReactJS poll

In my React code, I am fetching a poll using an API. However, I am facing an issue while working on the handleChange function for making a POST API request. The information required for the request includes PollId, userId, and answer. I am able to retrieve ...

Navigating through multiple pages with React Native stack navigation

I'm currently in the process of developing a react native app and I'm facing some confusion with regards to page navigation. It appears that there is a glitch in the navigation flow, causing it to skip a page. <NavigationContainer> ...

What is causing these TypeScript type assertions to go unnoticed?

While reviewing type assertions, I noticed something interesting about the last three variable assignments - they don't produce errors. It's perplexing because I thought I was trying to change 'helo' into 'hello', which should ...

Navigate within a JSON object using an identifier to extract a particular value associated with that identifier

Exploring a JSON object containing nested arrays and objects. The label value acts as the identifier to find and return its corresponding level's metrics value. If the label is located at the second level, retrieve and return the metrics from that lev ...

Angular - Automatically update array list once a new object is added

Currently, I'm exploring ways to automatically update the ngFor list when a new object is added to the array. Here's what I have so far: component.html export class HomePage implements OnInit { collections: Collection[]; public show = t ...

Potential dangers involved in sending HTML content through an AJAX request over a secure HTTPS connection

I am exploring the idea of dynamically loading HTML content, such as updating a Bootstrap modal dialog's contents using AJAX calls instead of refreshing the entire page. However, before I proceed, I want to understand the potential risks involved and ...