Search Filter for Live Select Dropdown in Angular JS

I have set up a newsfeed REST API to pull news items, along with a free text instant search feature.

Now, I am looking to incorporate a dropdown list search filter to allow users to filter news by author. How can I integrate a dropdown filter in a similar way to the free text search within the ng-repeat to filter results by author?

Check out this JSFiddle for reference.

app.js:

/* Newsfeed API Call */
var app = angular.module('newsFeed', [])
    .controller('Newsfeed', function($scope, $http) {
        $http.get('https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=6ddf8d3cc8a54cc0abf89ad7d685da54').
        then(function(response) {
            $scope.news = response.data;
            console.log(response.data.articles);
        });
    });

index.html:

<div class="container">
  <br/>
  <form>
    <div class="col-md-6">
      <h2>Newsfeed</h2>
      <br/>
      <div class="form-group">
        <input type="text" class="form-control" ng-model="searchText" name="search-news" id="search-news" placeholder="Search for news">
      </div>

      <div class="form-group">
        <select class="custom-select" ng-controller="Newsfeed">
          <option selected>Filter by Author</option>
          <option ng-repeat="n in news.articles | filter:searchAuthor | unique: 'author'" value="1">{{n.author}}</option>    
        </select>
      </div>        
    </div>
  </form>    

  <div ng-controller="Newsfeed">
    <div class="card" style="width: 20rem;" ng-repeat="n in news.articles | filter:searchText | filter:searchAuthor">
      <img class="card-img-top img-responsive" src="{{n.urlToImage}}" alt="Card image cap">
      <div class="card-block">
        <h4 class="card-title">{{n.title}}</h4>
        <p class="card-text"> {{n.description | cut:true:100:' ...'}}</p>
        <a href="#" class="btn btn-primary">Go somewhere</a>
      </div>
    </div>
  </div>
</div>

Answer №1

If you're looking to have your <select> filter the ng-repeat for articles, there is a way to achieve this.

By utilizing ng-options to populate values in your <select> and binding the selected value to the scope using ng-model, you can create the desired functionality:

<select ng-options="n.author for n in news.articles | unique: 'author'" ng-model="selectedAuthor">
    <option value="" ng-click="selectedAuthor = undefined">Filter by Author</option>
</select>

Afterward, you can simply filter the articles based on the selected author:

<div ng-repeat="n in news.articles | filter: searchText | filter: selectedAuthor">

Check out the working JSFiddle example here

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

"Process the contents of a file by reading it line by line in a

Currently, I am reviewing the documentation for the nodejs readline module in order to tackle a task that involves reading a very large file line by line. The solution using readline seems promising, although I require it to read lines synchronously - mean ...

When dealing with ReactJS, utilize the onChange event for handling updates to nested

I am currently learning ReactJS and struggling with a simple logic problem (I'm not very good at JS). I have a form that includes fields for name, email, and message. @ContactUsNew = React.createClass getInitialState: -> message: @props.mess ...

Modifying an array without altering the reference

Perhaps my approach is not quite right, so please provide feedback if necessary! Imagine having an Array that represents some valuable data. var initial = ['x', 'y']; var duplicate = initial; initial.push('z'); console.log(i ...

Signaling an Event from a module in the node_modules directory to the Vue application

Is there a way to capture an event emitted by a node module and receive it in a Vue file? Sample code from the JavaScript node module: const EventEmitter = require('events') class Find extends EventEmitter { // code snippets here } class Fin ...

Having trouble establishing a connection between Atlas and Node.js

Here is the content of my server.js file: const express = require('express'); const cors = require('cors'); const mongoose = require('mongoose'); require('dotenv').config(); const app = express(); const port = pro ...

React-redux: Data of the user is not being stored in redux post-login

Hello everyone, I am fairly new to using react-redux and I'm currently facing an issue with storing user information in the redux store after a user logs in. I am utilizing a django backend for this purpose. When I console out the user in app.js, it ...

Using jQuery Flot to dynamically load data onto the x-axis from an array

I have a jQuery flot graph that loads the x-axis data as follows: xaxis: { tickColor: 'transparent', tickDecimals: 0, ticks: ticks }, When I manually set the ticks variable like this, everything works fine and the x-axis displays the 7 da ...

What is the best way to showcase a component using FlatList?

Discovering the power of React Native combined with TypeScript and Redux Toolkit Hello! I'm currently facing an issue with rendering a list of messages using FlatList. Everything renders perfectly fine with ScrollView, but now I need to implement inf ...

What is the best way to restrict users from accessing more than 5 Bootstrap Tab-Panes at once?

Users are restricted to opening only a maximum of 5 tab panes, even if there are multiple tab buttons available. If the user tries to click on the 6th tab, an alert message will be displayed. function addTab(title, url){ var tabs=$(".tabs"), tab ...

Building Ext JS packages is an essential step in the development

Sencha command offers a seamless way to create, build, and distribute custom packages. The Ext JS library itself is constructed using Sencha command. I am curious about the process for ensuring that the built package maintains proper order, especially whe ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...

Guidelines for generating a sorted indices array from a different array using TypeScript

I need help finding a way to create an ordered array of indexes from another array in TypeScript. Let me provide some examples: imagine a function that takes an array of any length and returns another array with the indexes of the elements in ascending or ...

Filtering a list of data with Angular checkboxes

I've been exploring different options for implementing data filtering using checkboxes, but it all seems a bit too complex for something that I would expect Angular to handle easily. Feel free to check out http://plnkr.co/edit/Gog4qkLKxeH7x3EnBT0i T ...

Error: Attempting to access the `isPaused` property of a null object is not possible

For my Vue front-end app, I'm attempting to integrate wavesurfer.js. However, upon receiving the audio file link from the backend, I encounter the following error: wavesurfer.js?8896:5179 Uncaught (in promise) TypeError: Cannot read property 'isP ...

Having trouble grouping data on website due to duplicate names

Currently in the process of scraping data from various websites and looping through it. Specifically focusing on scraping the head section. This is an example illustrating the structure of the data: const head = { rel_data: [ { rel: &quo ...

What is the best method for initializing Bootstrap data attributes API?

I've been puzzled by this issue for a while now. When trying to use the JavaScript components, I can't seem to grasp how to utilize them using the Data Attributes API, also known as the first-class API. For example, take the modal component ment ...

What is the process for accessing API values in AngularJS?

Check out this API endpoint: Here is the JSON response: {"code":"S-QA501","message":"Success","result":[{"_id":"57f1f222fed49a24e02d5842","title":"how to improve metabolism?","revision":null,"author":{"userid":"","name":"","imageurl":"","followers":0,"si ...

Struggling to make a JavaScript program that sums up odd numbers

Let's tackle this challenge: Your task is to create a program that adds up all the odd numbers between 1 and the number provided by the user. For instance, if the user inputs 7, the program should calculate 1 + 3 + 5 + 7. The result of this calculati ...

Attempting to incorporate an audio file into a Discord.js module

My bot can join the voice channel successfully, but when I attempt to play audio, I encounter multiple errors indicating that I am missing certain modules [@discordjs/opus, node-opus, opusscript]. Although I have installed these modules, I am unsure of w ...

Using Jquery to create interactive and dynamic webpage elements

I am struggling with a paragraph containing words in a span that are editable upon clicking. The content needs to be dynamically called, but my current approach is not effective. Can anyone provide a solution or a better way to achieve this? Feel free to ...