angular: handling duplicates in ng-repeat

Here is the JSON data:

streams = [{ id: 0,
   codec_type: 'video',
   content: '1920x1040 - H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10' },
 { id: 1,
   codec_type: 'audio',
   content: '5.1(side) - cze - undefined' },
 { id: 2,
   codec_type: 'audio',
   content: '5.1(side) - eng - undefined' },
 { id: 3, codec_type: 'subtitle', content: 'cze - Czech' },
 { id: 4, codec_type: 'subtitle', content: 'eng - English' }];

This is how it looks in Angular HTML markup:

<md-input-container ng-repeat="stream in streams">
  <label>{{stream.codec_type}}</label>
  <md-select ng-model="stream">
    <md-option value="{{stream.id}}">{{stream.content}}</md-option>
  </md-select>
</md-input-container>

Hello! I am trying to locate duplicate strings within the JSON and display only one select field with multiple options for each duplicate (codec_type). Any suggestions on how to achieve this efficiently? Thank you!


!!! UPDATE !!!

I realize that I need to redesign the JSON structure and work with objects separately or employ a different approach for handling this situation.

You can find the CodePen link here..

Answer №1

To achieve your goal, you can utilize two different filters: one to extract a list of unique codec types and another to filter codecs based on their type.

Check out this CodePen example

Here is the HTML code:

<div ng-app="app">
  <div ng-controller="ctrl">
    <div ng-repeat="codec in streams | unique:'codec_type'">
      {{codec.codec_type}}
      <select ng-model="$parent.selected[codec.codec_type]" ng-options="stream as stream.content for stream in streams | codec:codec.codec_type track by stream.id">
      </select>
    </div>
    Selected streams: {{selected}}
  </div>
</div>

And here is the Controller code:

angular.module('app', [])
  .controller('ctrl', function ($scope) {
    $scope.selected = {
      'video': null,
      'audio': null,
      'subtitle': null
    };
    $scope.streams = [
      {
        id: 0,
        codec_type: 'video',
        content: '1920x1040 - H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10'
      },
      { id: 1,
        codec_type: 'audio',
        content: '5.1(side) - cze - undefined'
      },
      { id: 2,
        codec_type: 'audio',
        content: '5.1(side) - eng - undefined'
      },
      { id: 3,
        codec_type: 'subtitle',
        content: 'cze - Czech'
      },
      { id: 4,
        codec_type: 'subtitle',
        content: 'eng - English'
      }];
  })
  .filter('unique', function () {
    return function (items, id) {
      var filtered = [];
      var ids = {};

      angular.forEach(items, function (item) {
        if (typeof(ids[item[id]]) === 'undefined') {
          filtered.push(item);
          ids[item[id]] = true;
        }
      });

      return filtered;
    };
  })
  .filter('codec', function () {
    return function (items, codec) {
      var filtered = [];

      angular.forEach(items, function (item) {
        if (item.codec_type === codec) {
          filtered.push(item);
        }
      });

      return filtered;
    };
});

Answer №2

To implement the ngOptions directive, follow these steps:

For detailed instructions, refer to the AngularJS Documentation here

Here is an example code snippet:

<select ng-model="category" ng-options="category.name for category in categories>
   <option value=""> Select Category </option>
</select>

There are various ways to utilize ng-options, and the one showcased above is just one of them.

label for value in array

Refer to the provided link for a detailed explanation of each option available and select the one that best suits your requirements.

Answer №3

MASTERMIND:

let categories_array = [];
$scope.isDifferent = function (category) {
     if (categories_array.indexOf(category) === -1){
         return true;
     } else {
         categories_array.push(category);
         return false;
     }
}

MARKUP:

    <md-input-container ng-repeat="item in items">
         <div ng-if=isDifferent(item.type)>
             <label>{{item.type}}</label>
             <md-select ng-model="item">
                <md-option value="{{item.id}}">{{item.name}}</md-option>
             </md-select>
         </div>
    </md-input-container>

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

What could be causing my radio group to not validate when it is marked as required?

I am currently working with Angular 1.3.5 and I have a radio group that consists of two radio buttons. Both of these buttons share the same model called age. My goal is to make this group required so that an error message will be displayed if the user fail ...

Preventing select from opening when closing chip in Vuetify: A simple guide

Looking at this specific situation on vuetify.com https://codepen.io/anon/pen/RqoxXY?&editors=101 Regarding the autocomplete feature with chips, is there a way to prevent the select menu from opening when I cancel a chip? I attempted using @click.st ...

Is there a way to automatically redirect to a 404 page when a promise is rejected in the route configuration of Angular?

How should a client be directed to an error route in Angular when the API returns a 404 error while attempting to load a resource based on the parameters in the URL? In scenarios where a user accesses a page like orders/1, they should see the order detail ...

What is the best way to toggle the visibility of multiple column groups in Ag-Grid community using dynamic

I am seeking to replicate a basic version of the sidebar found in Ag-Grid Enterprise. The goal is to use JavaScript to gather all column groups within a grid and then provide a checkbox for each group to toggle visibility. While I am aware that individual ...

Attempting to access an avatar image via an API, only to encounter an error message indicating that the avatar is not defined

userData is a function that retrieves user data from an API using getUserByChainAccount. The username required by getUserByChainAccount is dynamically fetched from buyer. I'm trying to access the avatar, but I keep encountering the error message Unha ...

User currently signed in: What specific information should be transmitted to the web browser?

Experience: Currently utilizing the MEAN stack for a web application and still in the learning process. The Concern: I am facing some confusion regarding a particular aspect. For instance, if a user is logged in (using Passport.js), I can access their inf ...

I am having trouble getting the bootstrap link and css files to work on a specific URL. Can you please help me troubleshoot this issue and let me know if there are any additional files needed to

When attempting to apply the bootstrap link and css files to the URL "/list/:customListName", they are not working. However, changing the URL to "/:customListName" somehow makes it work. What is the reason behind this behavior and how can I properly style ...

Difficulty encountered while attempting to deploy the front-end on Heroku

I recently completed a typeorm project with the following structure: https://i.stack.imgur.com/ReQK1.png Both the client and root directories contain index files located in the src directory. In the package.json file within the client directory, I made a ...

Is there a way to transfer a JSON object to Excel using Nextjs/React?

How can I create a button that exports data from a JSON object to multiple file formats, including Excel (.xlsx)? "data": [ { "id": 1, "temaIndicador": "Indian", "codigo": "001", "observacion ...

Updating a numeric field in Mongoose by a percentage of its current value

Looking for a way to reduce prices of items in Mongoose. { name:"itemname", price: 30 } I want to apply a 10% reduction to the price, but $inc and $mul won't work for this scenario. {$mul: {price:0.10}} This code would reduce the price to 10% of t ...

Conceal a division on a webpage according to the URL of the specific

<script> function hideSearchField() { if (/menu/.test(window.location.href)) { document.getElementById('searchfield').style.display = 'none'; } } hideSearchField(); </script> I am trying to accomplish this using Jav ...

What can I do to resolve a node server issue with the error message "npm ERR! code ELIFECYCLE npm ERR! errno 1"?

npm ERROR! code ELIFECYCLE npm ERROR! errno 1 npm ERROR! [email protected] start: node server npm ERROR! Exit status 1 npm ERROR! npm ERROR! Task failed at the [email protected] start script. npm ERROR! This may not necessarily be an ...

Display a badge in the navbar on specific VueJS pages

I have embarked on the journey of creating a single page application using Vue 3, and I've encountered an interesting scenario where I want to display a badge in the navigation bar for specific pages. This is how my setup looks: // App.vue <templat ...

Utilizing AngularJS to invoke a jQuery plugin

Currently, I am utilizing the fullCalendar jQuery plugin alongside AngularJS. My goal is to call the refetchResources function of the jQuery plugin from Angular. I attempted to achieve this using the following code: angular.element(document.querySelector ...

Assigning a specific data type value to an element as it enters the top of the viewport

I have a unique color code stored for each section, and when a section reaches the top of the screen (specifically -180px for the header), I want to dynamically change the text color of the header element as you scroll through the sections. Despite no erro ...

There appears to be a glitch preventing Phonegap from properly syncing with Google Analytics

I'm currently developing an app using PhoneGap and I wanted to integrate Google Analytics into it. After installing this plugin via the CLI, I inserted the following lines of code within my deviceReady event: analytics.startTrackerWithId('UA-*** ...

Guide on transforming a collection of files from formdata into a JavaScript object

I have a dataset containing multiple images associated with the same product id. import client from "@/lib/fetchWrapper"; export default async function addProductImage({ photo, productId, }: { photo: File[]; productId: string; }) { if ...

How to effectively filter out negative numbers in AngularJS

How can I use ng-class in angularJS to display negative numbers in red and positive numbers in green? I need to apply a conditional CSS style based on the sign of the number using ng-class. How can I determine if a number is negative? <span ng-class=" ...

Angular2's $compile directive functions similarly to AngularJS 1's $compile directive

I am currently in the process of migrating my project from Angular 1 to Angular 2 and I am in need of a compile directive. However, I am struggling to rewrite it to achieve the same functionality as before. app.directive("compile", compile); compile.$inje ...

When the getImageData event is triggered upon loading

Hello, I have a script that identifies transparent and non-transparent pixels. Currently, the result is displayed from a 100px by 100px rectangle on mouseover: var data = ctx.getImageData(100,100, canvas.width, canvas.height).data; During mouseover, it s ...