Detecting Duplicates in an Angular JS Repeater and Handling the Not Allowed Exception

I am working on a task where I need to ensure that the object being added to an array of objects is not already present in a temporary array of objects.

While using AngularJS, I encountered an error stating "Duplicates in a repeater are not allowed." This error cannot be caught using try/catch blocks.

Is there a way to check for this specific exception or to verify if the object already exists in the array of objects?

Any assistance on this matter would be greatly appreciated.

CODE EXAMPLE:

  $scope.availableSounds = [
            {
                name: "Rain"
            },
            {
                name: "Storm"
            },
            {
                name: "Forest"
            },
        ];        

$scope.selectedSounds = [];

ADDING OF ITEMS (OBJECT IN THE ARRAY OF THE SELECTED SOUND SHOULD BE UNIQUE)

$scope.addSoundToSelection = function(index) {
            try {
                var selectedItem = $scope.availableSounds[index];
                $scope.selectedSounds.push(selectedItem);
                var pos = $scope.selectedSounds.map(function(e) { return e.hello; }).indexOf(selectedItem.name);
                console.log(pos);
            } catch(e) {
                $scope.showAlert();
            }
        };

Answer №1

Have you considered using the indexOf method?

var newObject = {};
var objectsArray = [ {}, {} ] //an array containing objects

if (objectsArray.indexOf(newObject) < 0) {
 objectsArray.add(newObject);
}

Alternatively, you could utilize the _.find method from the lodash library

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 are the steps to ensure that $.getScript functions properly?

It seems like the $.getScript function in jQuery will be really helpful once it's functioning properly, but I'm having some trouble with the last part. I have a feeling that the issue is related to how I'm loading JS files. How can I resolve ...

What is the best way to trigger the Javascript blur event following a click event that results in the element losing focus

Encountering this issue multiple times has left me dissatisfied with the solutions I've implemented in the past. The challenge lies in dealing with an input box that triggers a validation process on blur, while also having a button that populates the ...

Use PHP to redirect a webpage as an alternative to utilizing JavaScript

Recently, I encountered an issue where I created a form on inde1.php and utilized JavaScript to post data to login.php. My current goal is to redirect the user to another page once login.php has been successfully executed. Below is the JavaScript code on ...

How can I remove ASCII characters from an ajax response?

Experimenting with the API found at , but encountered an issue with properly formatting the received string. The string looks like this: Communication that doesn&#8217;t take a chance doesn&#8217;t stand a chance. The original response includes a ...

Error message indicating that the preflight request failed access control check in Angular 5 with JWT OAuth integration

After spending hours reading through several posts, I have yet to find a solution to a very common problem. It seems that in order for my JavaScript code to access the resource, the server must include the Access-Control-Allow-Origin header in the response ...

AngularJS and Ionic Framework - Click on a specific row to interact with it

I am struggling to open a new page when an item is touched in my HTML code. Despite trying multiple times, I can't seem to make it work and I'm at a loss as to why. Below is the snippet of my HTML: <!DOCTYPE html> <html> <hea ...

A guide to effectively converting and parsing a class object that includes Uint8Array elements

After stringifying a class object that contains a property in Uint8Array, and then parsing it later, the property is no longer in Uint8Array format. Here's an example: class Example { title:string; byteData:Uint8Array; ...

The module 'react/lib/React' could not be located within the file 'ReactTestUtils.js'

Setting up unit-tests for a React Native project using ReactTestUtils is causing an issue with npm test. The error message I receive is: Cannot find module 'react/lib/React' from 'ReactTestUtils.js' I suspect that my dependencies are ...

Tips for identifying when input fields have been altered within an AngularJS application

On my new page, users can input data without using a form. For example: <input type='text' ng-model='ExpReport.ReportName' /> <input type='text' ng-model='ExpReport.startdate' /> There is an exit button ...

The DiscordBot is configured to send a personalized direct message to users who have chosen a specific role

Having trouble setting up my bot to send a DM to new members who choose the Advertising role, and I can't figure out why. I'm fairly new to this. const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ ...

Jasmine tests for AngularJS directive failed to invoke the link function

I can't figure out why the link function of my directive isn't being called in a Jasmine test. I've created a simple example to illustrate. Here is the code for my directive (TestDirective.js): 'use strict'; angular.module(&ap ...

Is there a way to refresh the current page in Ionic 3 when the browser is reloaded?

I have encountered a problem in my work with an Ionic 3 App. I am looking for a solution where the browser will refresh the current page instead of redirecting me to the home page. Is this achievable? I attempted to solve it using the following code: thi ...

Testing AngularJS 1.5 controller state changes using unit testing with UI-Router

My AngularJS 1.5 application utilizes the UI-Router for state management, but I'm encountering difficulties with unit testing state changes within the controller. Here is the snippet of logic in my controller: CostingsController = ($scope, $http, $s ...

Can modifications be made to a page's source content variable using Ajax?

Can modifications be made to the source content of a page through Ajax loaded by a jsp include in the main jsp? If not, is it possible to refresh only that portion of the page (the jsp that loads some of the content) and have a portion of the content in t ...

Retrieving ID of an element to be animated with jQuery

I have a sprite image that changes background position when hovered over, and while it's currently working, I'm looking for a more efficient way to achieve this. I need to apply this effect to several images and am exploring ways to avoid duplica ...

Is it necessary to use the "new" keyword when utilizing JS closure to create objects?

My response to a question about closures on SO included the following code sample: function Constructor() { var privateProperty = 'private'; var privateMethod = function(){ alert('called from public method'); }; ...

I'm looking for a way to connect to my X-UI database using node.js - can anyone

I am looking to develop an app in node.js that will allow me to create my own RESTful APIs using a x-ui Xray graphical management panel. My goal is to be able to handle operations such as creating, editing, and retrieving data through the HTTP protocol. In ...

Iterate through the JSON data values using a loop and showcase each one by presenting them in individual cards

I'm having trouble determining which type of loop to use in this situation because I am still learning jQuery and JS. On the result page, I have set up cards to separate each piece of data from the JSON file, but I am unsure how to actually display th ...

Having trouble with Javascript's JSON.stringify or PHP's json_decode?

I am attempting to send an array from JavaScript to PHP. JavaScript: var json = JSON.stringify(extraFields); url += "&json="+json; PHP: $json = json_decode($_GET['json'], true); foreach($json as $K=>$V){ echo "json".$K . "=" . $V ...

What could be causing my mongoose array to remain empty without any values being stored in it?

Issue at Hand While I have come across several similar problems on Stack Overflow about this particular issue, none of the solutions provided seemed to work for me. I am in the process of developing a basic Forum application with two routes - one for cre ...