Creating a personalized <select> filter in Angular.js with two different JSON choices

I am working with a Q&A JSON feed that includes the following:

"questions": [
    {
      "answer": "Ea et non sunt dolore nulla commodo esse laborum ipsum minim non.", 
      "id": 0, 
      "poster": "Chelsea Vang", 
      "question": "Ex ex elit cupidatat ullamco labore quis cupidatat. Reprehenderit occaecat mollit ex proident aliqua. Anim minim in labore pariatur adipisicing velit dolore elit nostrud proident reprehenderit in voluptate.", 
      "userAsked": false
    }, 
    {
      "answer": null, 
      "id": 1, 
      "poster": "Serena Randolph", 
      "question": "Esse occaecat anim cupidatat eu sit ad eiusmod. Et tempor deserunt ea ipsum velit irure elit qui. Ipsum qui labore laboris Lorem occaecat enim Lorem exercitation ut non duis. Sit cillum incididunt culpa ipsum.", 
      "userAsked": true
    }
  ]

I need to develop a custom filter for filtering the results by selecting dropdown options such as: All Questions, "My Questions" (userAsked: true), and Answered Questions. I'm familiar with creating filters for single objects but unsure how to implement it in this scenario where multiple options need to be filtered. I can't use ng-repeat for select options due to multiple criteria selection.

Here is a snippet of my view:

<select>  
 <option value="all">All Questions</option>  
 <option value="answered">Answered Questions</option>  
 <option value="mine">My Questions</option> 
</select> 

<ul class="list-unstyled">  
 <li ng-repeat="questions in qa.questions">   
  <strong>Question:</strong><br>
  {{questions.question}}<br>   
  <strong>Answer:</strong><br>   
  {{questions.answer}}    
  <hr>  
 </li> 
</ul>

Controller:

sessionControllers.controller('SessionDetailCtrl', ['$scope', '$routeParams', 'SessionFactory', 'CommentsFactory', 'QAFactory', function($scope, $routeParams, SessionFactory, CommentsFactory, QAFactory){
    $scope.session = SessionFactory.get({id: $routeParams.id});
    $scope.comments = CommentsFactory.get({eventId: $routeParams.id});
    $scope.qa = QAFactory.get({eventId: $routeParams.id});  
}]);

If anyone can assist me in implementing this filter, I would greatly appreciate it!

Answer №1

Thanks to the helpful suggestions from @tymeJV, I was able to successfully implement the solution.

Check it out

<select ng-model="filterItem.question" ng-options="item.questionType for item in filterOptions.questions">  
 <option value="All Questions">All Questions</option>  
 <option value="Answered Questions">Answered Questions</option>  
 <option value="My Questions">My Questions</option> 
</select> 

<ul>
 <li ng-repeat="questions in qa.questions | filter: myCustomFilter">
   <strong>Question:</strong>
   <br>{{questions.question}}<br>
   <strong>Answer:</strong><br> 
   {{questions.answer}}
 </li>
</ul>

Controller

$scope.filterOptions = {
    questions: [
      {questionType: 'All Questions'},
      {questionType: 'Answered Questions'},
      {questionType: 'My Questions'}
    ]
  };

  //Mapping model for filtering
  $scope.filterItem = {
    question: $scope.filterOptions.questions[0]
  };

  //Custom filter - based on selected Question Type
  $scope.myCustomFilter = function (data) {
    if ($scope.filterItem.question.questionType === "All Questions") {            
      return true;
    } else if ($scope.filterItem.question.questionType === 'Answered Questions') {
      return data.answer != null;
    } else if ($scope.filterItem.question.questionType === 'My Questions') {
      return data.userAsked;
    }
  };

Answer №2

Why not try adding a model to your select filter and implementing it like this:

<select ng-model="filterQuestions">  
   <option value="all">All Questions</option>  
   <option value="answered">Answered Questions</option>  
   <option value="mine">My Questions</option> 
</select> 

<li ng-repeat="question in qa.questions | filter: customFilter">

For the controller, you could use:

$scope.customFilter = function(item) {
    if (filterQuestions == "all") {            
        return true;
    } else if (filterQuestions == "answered") {
        return item.answer != null;
    } else if (filterQuestions == "mine")
        return item.userAsked;
}   

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

If there is a value in the array that falls below or exceeds a certain threshold

Imagine you have a set number of values stored in an array and you want to determine if any of them fall above a certain threshold while also being below another limit. How would you achieve this? Provide a solution without resorting to using a for loop o ...

Generate PDF Files Using Ajax

Currently, I am utilizing FPDF to generate my report. $pdf = new Report('P','mm','A4', $_POST); $pdf->AddPage(); $pdf->Output('file.pdf','I'); Furthermore, I am employing ajax to send a request to t ...

Can you explain NodeSource in simple terms, and what purpose does it serve?

Not too long ago, I delved into researching how to effectively host a MEAN stack web application on AWS. During my quest for knowledge, I stumbled upon a tutorial that caught my eye. The one I ended up following can be found at https://www.youtube.com/wat ...

Is it possible to use a shell script to replace the external CSS file link in an HTML file with the actual content of the CSS file

Seeking a solution for replacing external CSS and JS file links in an HTML document with the actual content of these files. The current structure of the HTML file is as follows: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C ...

Guide on setting a JSON object using the getJSON method

In my coding project, I am trying to assign values of lat and lng from a JSON object named branch to a variable called jsonData. When I use console.log to check jsonData.responseJSON.positions.length or jsonData.responseJSON.positions[0].lat, etc. I c ...

Select box failing to display default value

I am dealing with a specific data structure: $scope.personalityFields.traveller_type = [ {"id":1,"value":"Rude", "color":"red"}, {"id":2,"value":"Cordial", "color":"yellow"}, {"id":3,"value":"Very Friendly", "color":"green"}, ]; Also, there is a se ...

Getting files onto your device - the Phonegap way

I'm having trouble exporting or downloading information to a file. It works fine in my browser, but when I try it in my phonegap app, the file just opens as text without an option to save it or return to the app. Any advice? Keep in mind that I'm ...

Using jQuery to select a div element that has been dynamically loaded using ajax, or inserted into the DOM using the html()

Greetings from a newcomer to stackoverflow! After searching for similar questions and answers, I still couldn't find a solution to my specific problem. Here's the situation: I have a webpage that uses ajax to load main content. The function for ...

Transform a JSON object string into a usable value

I'm currently working on a function that takes a string, splits it, and then formats it using json[key][key2][key3]. The issue is that 'n' could potentially be infinite (not literally but needs to be written as such) function getJsonValue(j ...

Enhance Your Website with Interactive Tooltips Using Twitter Bootstrap

In Twitter bootstrap, the default trigger for tooltips is hover. If I want to make the tooltip display on focus instead, I can add data-trigger="focus". But how do I make it so the tooltip displays both on hover and on focus? ...

Creating a straightforward Theme Changer feature using Vue.js

Check out this tutorial for creating a simple Dark/Light theme switcher using Tailwind CSS. This tutorial utilizes vanilla JS and only requires a single app.js file. If I want to incorporate this into a Vue project, should I simply paste the code into ~/s ...

When the Angular script is executed, the variable is not defined

One of my custom directives receives an object named 'vm' in its scope, which contains a property/value pair (ccirCategoryIncidentI : 3) that I need to access. When I try to log this value with console.log(scope.vm.ccirCategoryIncidentI), it init ...

What are some effective techniques for leveraging ElasticSearch's term queries in order to refine results by searching for a specific value within an array

I'm trying to make a POST request to an API in order to receive only the hits with the role "editor". The initial response, without any filters, appears as follows: _source: { configuration: { roles : [ {role : "lead"}, {role ...

Guide to resolving a blank webpage issue post running 'npm run build'

I am currently in the process of working on a project that involves Vue and Firebase. Unfortunately, I have encountered an issue where my development server is no longer rendering new routes from my Vue router after building and deploying to production. F ...

I am unable to extract the information from a JSON formatted string

Looking to extract some option data from a JSON encoded string, this is the current code: <?php $json = json_decode('{"1":"{\"QID\":\"1\",\"Type\":\"MC\",\"Question\":\"Question here\",&b ...

Learn how to import from a .storybook.ts file in Vue with TypeScript and Storybook, including how to manage Webpack configurations

I'm currently utilizing Vue with TypeScript in Storybook. Unfortunately, there are no official TypeScript configurations available for using Vue with Storybook. How can I set up Webpack so that I am able to import from another .storybook.ts file with ...

Tips for selecting and utilizing a drop-down menu in JavaScript

Having an issue with the drop-down list functionality. It seems to only work with the first option selected and not with all of them. Any assistance would be greatly appreciated. Thank you in advance. var form1 = document.getElementById('form1' ...

Issue encountered: Module 'jasmine-expect' not found [Protractor]

I am facing an issue while trying to execute a protractor test that connects to my application. Upon running the command (git bash/terminal): protractor conf.js An error is displayed as follows: " Error: Cannot find module 'jasmine-expect&apo ...

Play 2.4's trait JSON formatter utility

I am encountering an issue trait Role[A, B] { val _id: Option[A] = None val value: Option[List[B]] = None val id: Option[String] = None } There is a case class that extends the above trait case class User (value1: Option[Role] = None, v ...

Exploring JavaScript Object-Oriented Programming (OOP) concepts. Delving into the

Here is a sample of JavaScript OOP that I am currently studying. I'm puzzled about why getA() and getC() are returning undefined, but getB() returns 2 when I update the variable B in the constructor and assign it to b. When I execute getD(), it appea ...