ng-repeat to prevent duplicate items from displaying

I intentionally have duplicates in my array of items and I am looking for a way to hide just one of them when clicked within my ng-repeat.

Is there a way to hide only one of the duplicated items on click?

I feel like I might be overlooking something, as I am having trouble figuring it out.

Check out the Plunker example

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

app.controller('MainCtrl', function($scope) {
  var users = [{name: 'toto', hide:false},{name: 'titi', hide:false},{name: 'tutu', hide:false},{name: 'tata', hide:false}];
  
  $scope.doubledUsers = [].concat(users, users);
  
  $scope.hideUser = function(user){
    user.hide = true;
  }
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</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="2f4e41485a434e5d01455c6f1e011a0157">[email protected]</a>" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

    <body ng-controller="MainCtrl">
    <div ng-repeat="user in doubledUsers | orderBy: 'name' track by $index">
      <p ng-hide="user.hide" ng-click="hideUser(user)">Hello {{user.name}}! - id={{$index+1}}</p>      
    </div>

  </body>

</html>

Answer №1

Indeed, your reasoning is accurate, however, the issue lies within this particular line of code:

$scope.doubledUsers = [].concat(users, users);

By executing this line, the same reference is duplicated for the users, resulting in two elements being concealed when hidden.

DEMO

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

app.controller('MainCtrl', function($scope) {
  $scope.users = [{name: 'toto', hide:false},{name: 'titi', hide:false},{name: 'tutu', hide:false},{name: 'tata', hide:false}];
  
 // $scope.doubledUsers = [].concat(users, users);
  
  $scope.hideUser = function(user){
    user.hide = true;
  }
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</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="e0818e87958c8192ce8a93a0d1ced5ce98">[email protected]</a>" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

    <body ng-controller="MainCtrl">
    <div ng-repeat="user in users | orderBy: 'name' track by $index">
      <p ng-hide="user.hide" ng-click="hideUser(user)">Hello {{user.name}}! - id={{$index+1}}</p>      
    </div>

  </body>

</html>

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

Unleashing the Power of Json Strings

After searching for 7 years, I have come across this old unanswered question: getting value from json string php. I am in need of assistance as my code is in the following format: Upon using json_decode(), the var_dump output was: String(384) “{“dat ...

What is the best way to create an AngularJS page with a direct link that will dynamically affect the content on the

I have a webpage similar to Google search where the backend generates a list of items. The page features an HTML form with multiple fields for users to modify values, resulting in a refreshed list of items from the backend. Currently, users can create a ...

Can you explain the purpose of $winstonLoggerConfig<T>() and $winstonLogger<T>() in winston v3?

I'm currently using the winston logger and I want to implement flow typing for it. However, I am unsure of what exactly I should pass to it in order to achieve this. Below is my current logger setup: const logger = createLogger({ ... }); Missing typ ...

Using ng-include destroys the styling of the dropdown menu in a bootstrap ul li format

Greetings! I am attempting to replicate the following code snippet that creates a basic dropdown menu using bootstrap: <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="fal ...

How to Handle Empty Input Data in JQuery Serialization

Having an issue with a form that triggers a modal window containing another form when a button is clicked. The second form includes an input field and send/cancel buttons. The goal is to serialize the data from the modal form and send it to a server using ...

What could be the reason for the malfunctioning of the header() function in PHP

Currently, I'm utilizing AJAX to facilitate user registration for a service. Here's the code snippet for the submit button: <input type="button" id="register" name="register" class="btn btn-success" onclick="registration();" value="Register"/ ...

Troubleshooting AngularJS binding problem when using ngRepeat to handle Collapse and Expand Caret icon

I am experimenting with implementing collapsible and expandable panels within an ngRepeat loop. Here is my approach: <tbody ng-repeat="item in Items"> <tr data-toggle="collapse" class="accordion-toggle"> <td>{{item.name}}< ...

The Next.js dynamic route in production is displaying a 403 error instead of the expected 404. What might be causing this issue?

Whenever I attempt to access https://site.con/categories/, I am greeted with a 403 Forbidden error. However, if I visit https://site.con/categories/sport, everything works perfectly fine, and all other routes function properly. What could potentially be ca ...

Managing data from devices by using Ionic v2 along with the BLE Central plugin

Currently experiencing some difficulties when it comes to managing the device data of discovered peripherals. I am searching for some guidance on this matter. I can successfully scan for devices and my "success" callback functions without any issues. My g ...

Click event not triggering for selected option in jQuery dropdown menu

After adding dropdown anchor tags dynamically to the drop-down menu, the click event does not seem to be firing. Do I need to re-bind the click handler after using .append, or should I wrap the click handler in a function? <script src="https://code.jqu ...

Issue encountered while working with PostgreSQL and Sequelize when using the array_append function

I'm encountering issues with the following code snippet let user = req.user.id; await MyTable.update( {'interested': Sequelize.fn('array_append', Sequelize.col('interested'), user)}, {'where ...

Minimizing switch-case statement into inactive input field (AngularJS)

While the code statement functions as intended, it may not be considered best practice due to the repetition of variables in each case of the switch statement. I am unsure of how to streamline the code or if there is an alternative to using a switch statem ...

Using React to redirect a category of components to a specific sub-path, such as transforming "/templates" to "/templates/list"

Having a React app, I'm looking for a way to avoid duplicating the function of redirecting users to /<component>/list in every component if they visit just /<component>. How can this be achieved at a higher level? I have a layout componen ...

Using Three.JS 'OrbitControls' in VueJS application results in a black screen appearing?

Currently, I've been delving into the basic cube exercise on Three.js, and incorporating the three.js cube into my Vue.JS application. Initially, everything was functioning smoothly, with my cube rotating as intended using animate, etc. However, thi ...

What causes discrepancies between jQuery set attributes and .html() output?

In an attempt to set attributes on HTML snippets, I am aiming to repopulate a form with previously entered values. Despite using .attr() to set the attributes, they do not appear after using .html(). For reference, I have provided a simple example here: h ...

Encountering Uncaught Promise Rejection Warning in Node.js

I can't figure out why I am receiving this error or warning when my code appears to be correct. Below is a snippet of the UserModel that I have been working on: const fs = require('fs'); class UserModel { constructor(filename) { ...

Menu with hover functionality in JQuery that functions as a standard menu even when JavaScript is disabled in the browser

Is it possible to modify this code so that the hover point links' images do not appear if the browser has JavaScript disabled? And can the links function like a regular hover point even when JavaScript is disabled? <script type="text/javascript" s ...

Utilize $.ajax to gracefully wait for completion without causing the UI to freeze

Consider a scenario where there is a JavaScript function that returns a boolean value: function UpdateUserInSession(target, user) { var data = { "jsonUser": JSON.stringify(user) }; $.ajax({ type: "POST", url: target, data: ...

What is the reason behind obtaining a distinct outcome when logging the properties of an object compared to logging the object itself and checking its properties?

Currently, I am working on integrating socket-io with react redux and encountering a peculiar namespace problem. console.log(socket); console.log(socket.disconnected); console.log(socket.id); console.log(socket); The first log displays a comprehensive ob ...

Sharing State with a Secure Route in Vue Router (using the script setup method)

Hello everyone, I'm encountering an issue while trying to send a state to the protected routes in vue-router. The error that I faced mentioned "Discarded invalid param(s) "_id", "dish_name", "description", "img" ...