Searching for "unique elements" using AngularJS ng-repeat

I am trying to organize a list by category, but the challenge is that each category input is customized and can be added by any user in the list.

My initial attempt involved using ng-repeat to filter out duplicate values (as seen in the code snippet unique:'Category' below). I set the Category name as the filter value and also included an "All" category option to display all elements:

<ul class="categoriesList">
  <li>
    <label>
      <input type="radio" ng-model="searchCategory.Category" value=""> All
    </label>
  </li>
  <li ng-repeat="x in myList | unique:'Category'">
    </label>
      <input type="radio" ng-model="searchCategory.Category" value="{{x.Category}}"> {{x.Category}}
    </label>
  </li>
</ul>

Unfortunately, this method is not yielding the desired results. Here is a Plunker example demonstrating my issue: Link to Plunker

I need a solution that allows for the addition of any custom category in the JSON data example, while still being able to effectively filter them. Thank you in advance for your help.

Answer №1

It was a simple fix needed for the issue in your code - just defining the searchCategory property on the $scope. By adding $scope.searchCategory = {}; to your controller, you can resolve the problem. The reason behind this is that ng-repeat creates its own child scope. Here's a snippet with the corrected solution.

Another thing that was missing was assigning the same group to all radio buttons so that only one can be selected at a time. This can be done by adding the name='filter' attribute to each radio button.

Your updated AngularJS filter:<!DOCTYPE html>
<html ng-app="app">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Filter with custom values</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90f1fef7e5fcf1e2befae3d0a1bea4bee8">[email protected]</a>" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <ul class="categoriesList">
    <li>
      <label>
          <input name="filter" type="radio" ng-model="searchCategory.Category" ng-value=""> All
        </label>
    </li>
    <li ng-repeat="x in myList | unique:'Category'">
      <label>
          <input name="filter" type="radio" ng-model="searchCategory.Category" ng-value="x.Category"> {{x.Category}}
        </label>
    </li>
  </ul>

  <div class="wrapper" ng-repeat="y in myList | filter:searchCategory:true">
    <ul class="click-text">
      <li>{{y.Title}} - {{y.Comments}}</li>
    </ul>
  </div>
</body>

</html>

I hope this explanation and the revised code helps :)

Answer №2

Make sure to include the Ex- name="rdoCategory" attribute for the radio button

`<ul class="categoriesList">
      <li>
        <label>
          <input type="radio" name="rdoCategory" ng-model="searchCategory.Category" value=""> All
        </label>
      </li>
      <li ng-repeat="x in myList | unique:'Category'">
        </label>
          <input type="radio" name="rdoCategory" ng-model="searchCategory.Category" value="{{x.Category}}"> {{x.Category}}
        </label>
      </li>
    </ul>`    

Once you do that, the functionality should work as expected.

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

Receiving a sleek black overlay with dynamic text upon hovering over an image

I have been searching extensively for a solution to my issue, but I haven't been able to make it work in my application. What I want is to create a black overlay over an image when it is hovered over, with text that resembles a button appearing on top ...

What is the best way to utilize bilinear color interpolation with JavaScript?

I'm grappling with the concept of bilinear interpolation, wondering if there's a more efficient method than what I've attempted below using the Culori library's interpolate() function. My uncertainty lies in whether it's correct t ...

Using Jquery, insert a line break when a specific character is entered in a text area by pressing the Enter button

$('.text-description').keyup(function () { var count = $(this).val().length; if(count == 63){ //insert line break here } }); When the character count reaches 63, including spaces, I want the cursor to move to the next line (sim ...

Working with promises and Async/Await in Express/node can sometimes feel ineffective

Currently, I am delving into the world of node and express with the aim to create a function that can extract data from a CSV file uploaded by the user. My challenge lies in the fact that the data is being outputted as an empty array before it goes through ...

Adjust the aesthetic based on whether the field is populated or empty

I have a simple text field on my website that triggers a search when the user inputs a value. I am wondering if it is possible to style the text field differently depending on whether it is empty or has content. Specifically, I want to change the border c ...

What could be the reason why a specific item is not being retrieved by its ID?

Whenever I navigate to the route: '/gallery', all the items from the file './posts.json' are fetched and displayed on the screen. However, upon navigating to the route: '/gallery/:id', my intention is to retrieve a single item ...

Arranging cards in a stack using VueJS

I am currently working with a small vue snippet. Originally, I had v-for and v-if conditions in the snippet, but due to issues reading the array, it is now hardcoded. The current setup produces three cards stacked on top of each other. I am exploring opti ...

Error message: "Unable to POST image with Node/Express (React frontend) while attempting to upload

I am a beginner in Node.JS and currently working on developing a MERN movie ticket booking system. The front-end code snippet provided below showcases the function responsible for uploading an image for a specific movie: export const uploadMovieImage = ( ...

Obtain the parameter of a parent function that runs asynchronously

Here's the code snippet I'm working with: function modify( event, document ) { console.log( "document name", document ); //I need it to be 'file', not 'document'. documents.clients( document, function( clientOfDocument ...

Error code 403 has been reported by Stripe's payment_init.php as a forbidden request

Having some trouble incorporating a Stripe payment method into my web application. I've hit a roadblock: payment_init.php isn't loading when I'm redirected to the page. Instead, I'm greeted with a 403 Forbidden error code ("Forbidden. Y ...

Applying a class change in Vue.js upon mounting

How can I make a button element with a .hover property trigger the hover animation as soon as the page loads? I want to apply a class to the button when the page is mounted and then remove it later. What is the best approach for this? I considered using a ...

Is there a way to change a .pptx document into a base64 string?

Currently, I am working on a project that involves creating an addin for Office. The challenge I am facing is opening other pptx files from within the addin. After some research, I discovered that I need to use base64 for the PowerPoint.createPresentation( ...

What could be causing my SVG bezier curves to malfunction in Firefox?

Encountered an issue today where diagrams I have generated are not functioning properly in Firefox when created using the getPointAtLength method. Here is a demonstration of the problem: http://jsfiddle.net/xfpDA/9/ Please take note of the comments at th ...

Break up every word into its own separate <span>

I am currently facing an issue with displaying an array of strings in HTML using spans. These spans are wrapped inside a contenteditable div. The problem arises when a user tries to add new words, as the browser tends to add them to the nearest existing sp ...

When attempting to execute a Spring Boot CLI using the command "spring run app.groovy", an error is displayed stating "bash: spring: command not found"

When running the following command in git bash: $ spring run app.groovy An error is encountered, bash: spring: command not found The content of app.groovy includes: @Controller class JsApp { } ...

Is it possible to efficiently update the innerHTML of multiple div elements using a single function?

Upon clicking a button, I am dynamically updating the content of multiple divs using innerHTML. Currently, the button triggers a new video source to load, but I also want to change other types of content in different divs at the same time. I wonder if cha ...

what's the reason for ajax constantly sending requests back-to-back?

Today, I find myself pondering. In my current project, the ajax calls are not behaving asynchronously. Each request is being sent one after the other. As one request is being processed, all other requests are getting stuck in a pending state. You can ob ...

Content changing programmatically does not reset the scrollHeight

As I embark on the journey to expand my coding skills, I have decided to challenge myself by tackling some tasks without relying on jQuery. One particular challenge that I am currently facing involves a fixed contenteditable div. The goal is to adjust the ...

React fails to trigger a re-render despite updating the state following an API call

Recently, I started working with React and attempted to retrieve data from my API. However, changing the state does not trigger a re-render of the component. Inside the useEffect function in my component, I have code that fetches the API and then sets the ...

Use leaflet.js in next js to conceal the remainder of the map surrounding the country

I'm currently facing an issue and would appreciate some assistance. My objective is to display only the map of Cameroon while hiding the other maps. I am utilizing Leaflet in conjunction with Next.js to showcase the map. I came across a helpful page R ...