Using Angular's ng-repeat to handle duplicate elements

My chosen front-end framework is Angular, and below is an example of how I structure my view:

   <div class="col-sm-6" ng-repeat="contact in service.contacts">

    <label class="control-label mb10">{{contact.textDescription | decodeURIComponent}}</label>
               <select  multiple="multiple" selectize>
                   <option>{{contact.value}}</option>
              </select>

     </div>

I am facing a specific issue that I'm struggling to resolve. When it comes to the contact.textDescription field, I only want unique values to be displayed. If a duplicate textDescription is encountered, I do not want to create a new field. Instead, I want to simply add the contact.value to the options of the existing textDescription entry. Here's an idea of what I am trying to achieve:

if(contact.textDescription is duplicate) {
 contact.value.addTo(contact.textDescription which already exists)
}

I am considering applying a filter to address this problem. Any suggestions on how to approach this?

Answer №1

Based on the information you provided, I believe utilizing the filter mentioned in the subsequent response will assist you in achieving your desired outcome.

Click here to access the related question

Answer №2

Utilize ng-options for organizing and showcasing distinctive values.

Answer №3

If you want to filter out duplicates, you can utilize the uniqFilter from the angular-filter module.
To use: Simply apply the filter like this: collection | unique: 'property' or nested.property
Alternative names: You can also use uniq

Here is an example:
In JavaScript:

function MainController ($scope) {
  $scope.orders = [
    { id:1, customer: { name: 'John',    id: 10 } },
    { id:2, customer: { name: 'William', id: 20 } },
    { id:3, customer: { name: 'John',    id: 10 } },
    { id:4, customer: { name: 'William', id: 20 } },
    { id:5, customer: { name: 'Clive',   id: 30 } }
  ];
}

In HTML:

<th>Customer list:</th>
<tr ng-repeat="order in orders | unique: 'customer.id'" >
   <td> {{ order.customer.name }} , {{ order.customer.id }} </td>
</tr>

RESULT:

Customer list:
- John 10
- William 20
- Clive 30

Answer №4

Arranging your connections based on textDescription can help you solve the issue at hand. You may want to consider implementing something similar to the following:

html:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example - GroupBy Filter</title>

    <script src="angular-1.4.7.min.js"></script>
    <script src="script.js"></script>

</head>
<body ng-app="app">
    <div ng-controller="MainController">
        <div ng-repeat="(key, contacts) in (service.contacts | groupBy: 'textDescription')">

            <label class="control-label">{{key}}</label>
            <select  multiple="multiple" selectize>
                <option ng-repeat="contact in contacts">{{contact.value}}</option>
            </select>
        </div>
    </div>
</body>

script.js:

var app = angular.module("app", []);

app.controller("MainController", function ($scope) {
    $scope.service = {};
    $scope.service.contacts = [{
        "textDescription": "td1",
         "value": "1"
    }, {
        "textDescription": "td2",
         "value": "2"
    }, {
        "textDescription": "td3",
        "value": "3"
    }, {
        "textDescription": "td1",
        "value": "4"
    }, {
        "textDescription": "td3",
        "value": "5"
    }, {
        "textDescription": "td1",
        "value": "6"
    }];
});

app.filter('groupBy', function () {
    var results={};
    return function (data, key) {
        if (!(data && key)) return;
        var result;
        if(!this.$id){
            result={};
        }else{
            var scopeId = this.$id;
            if(!results[scopeId]){
                results[scopeId]={};
                this.$on("$destroy", function() {
                    delete results[scopeId];
                });
            }
            result = results[scopeId];
        }

        for(var groupKey in result)
            result[groupKey].splice(0,result[groupKey].length);

        for (var i=0; i<data.length; i++) {
            if (!result[data[i][key]])
                result[data[i][key]]=[];
            result[data[i][key]].push(data[i]);
        }

        var keys = Object.keys(result);
        for(var k=0; k<keys.length; k++){
            if(result[keys[k]].length===0)
                delete result[keys[k]];
        }
        return result;
    };
});

Your contacts are now grouped by textDescription, ensuring that the field for it (<label>) is only generated once and values are appended to <option> tags accordingly.

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

Issue encountered in React Native Expo: Attempting to access an object that is undefined while evaluating item.basicData.criminalName

const SearchContext = React.createContext(); class SearchProvider extends Component { state = { tfG: false, aboutToSearch: "criminals", }; render() { return ( <SearchContext.Provider value={{ state: t ...

Create a never-ending jQuery script that is simple and straightforward

My WordPress website features an accordion element that usually functions well by toggling classes when tabs are clicked. However, there is one issue where clicking on a tab does not automatically close other opened tabs. To address this, I added the follo ...

The storage format of the input field is handled differently on the angularjs controller side

Check out the plunker link for this directive in action. A comma is automatically added as the user types in the input, and it displays numbers with 2 decimal places. However, there seems to be an issue where entering '2300.34' results in ' ...

Acquire the selected option's value and display it within a div container

Is there a way to extract and display only the price value (after the " - ") within a div with the id of "price", updating as the select element is changed? <select id="product-select" name=""> <option value="1">Product Name / Yellow / S - ...

Retrieving Data from a Nested JSON Array

How do I modify my JavaScript code to extract the last 3 values from the JSON list provided below? The current code is unable to read these values with different formatting. Example section of the JSON list: {...... 'Design_Lump_Sum': {0: {&a ...

Emphasize Expandable Sections based on Search Term

I have been working on developing an HTML page for my company that will showcase a list of contacts in an "experts list". Currently, the list is structured using collapsible DIVs nested within each other. Additionally, the HTML page features a search func ...

Using JavaScript for Array manipulations

Here's a string that I want to convert into an array: "["Arr1","Arr2"]" To achieve the desired format, I need to remove the first and last characters so it looks like this: ["Arr1","Arr2"]. I've attempted using the slice function in this wa ...

The method _react.default.useContext does not exist as a function

I am currently working with Material UI Stepper. After using it, I noticed that the functionality is not working properly as expected from their website. To troubleshoot, I added a console.log inside the VerticalLinearStepper method. Upon checking the cons ...

Tips for uploading information and posting it on a different page with mongoDB and Node.js

I am looking to implement a feature on a website where data is submitted to MongoDB from one page, and then retrieved and displayed on another page. The technologies I am working with include node.js, express, Mongoose, and MongoDB. Currently, the data is ...

Ensure that the input button for uploading is only accessible when checked and is marked as

Most of my previous questions have been about input boxes and SQL, as I am still in the learning process. Any help is greatly appreciated. My current question revolves around displaying a button to upload an image using PHP (although for this example, I w ...

Issue: Experiencing multiple re-renders when attempting to send a post request to the backend using

export default function CRouter() { const [token, setToken] = useLocalStorage('auth', '') const [user, setUser] = useState(false); const GetUser = () => { if (token !== "" && !user) { axios.post(&apo ...

Dealing with a 409 conflict situation involving a document in Node.js using Nano library

After conducting research, it has come to my attention that there are numerous document conflicts with couchdb. While exploring a potential solution in Updating a CouchDB document in nano, I discovered the following steps: Retrieve the document Store th ...

How can objects be merged within an array and a new object be inserted?

I have an array of objects representing podcasts in a podcast app. Here is how the data looks: [{ id: "uuid-1" timeInSeconds: 1000 dateListened: "2021-01-01T15:57:17.000Z" }, // <---same day { id: "uuid-2" timeInS ...

How to use Ionic 3 to automatically scroll ion-scroll content all the way to the bottom

My ion-scroll component is experiencing some challenges <ion-scroll scrollY="true" style="height: 52vh;"> {{ text }} </ion-scroll> The content inside the ion-scroll keeps expanding, exceeding the designated height. Users can manually scroll ...

Importance of value attribute in <input ng-model ..>

Maybe a silly inquiry, but I'm curious about the purpose of having value="" in this particular situation: <input ng-model="something.name" value="" class="input-xlarge" /> Are there any alternatives to keeping the value attribute empty? I init ...

Is there a better way to remove the hidden attribute from p2 since calling removeAttribute() doesn't appear to work?

Is there a way to successfully change the attribute of an object using removeAttribute to remove its hidden status? I've been attempting this but haven't had any luck so far. It seems like my code isn't having any effect. Could I be making ...

Tips for gently scrolling instead of quickly scrolling all at once

As a novice in HTML, I have a question about navigation to an ID targeted by an anchor tag. For example: When I execute this code, it quickly jumps to the specified ID but I would like to incorporate animations. Is there a way to achieve this? ...

Combining and Reorganizing JSON Data with Arrays of Objects

Seeking assistance after spending a considerable amount of time on this task. Our objective is to dynamically merge two JSON responses by utilizing the data from JSON Data 2 (prodsub_id) with JSON Data 1 (id). Refer to the sample JSON data below. JSON Dat ...

Guide on incorporating a dropdown menu within a Jssor slider

I am facing an issue with trying to include a dropdown menu inside the Jssor slider. The menu does not drop down when placed inside it. Here is the code snippet: <head> <script src="jquery.js"></script> <script src="jssor.slider.min. ...

I'm having trouble managing state properly in Safari because of issues with the useState hook

Encountering Safari compatibility issues when updating a component's state. Though aware of Safari's stricter mode compared to Chrome, the bug persists. The problem arises with the inputs: https://i.sstatic.net/WSOJr.png Whenever an option is ...