AngularJS - Shared service object mistakenly removed in error

When I call the removeQuestion() function for the second time, 2 questions are being deleted instead of one. Any suggestions on what might be causing this issue? Let me know if you require additional code snippets.

controller.js

crtPromoCtrl.controller('surveyCtrl', ['$scope', 'surveySrv', function($scope, surveySrv)
{
    $scope.questions = surveySrv.getQuestions();

    $scope.editQuestion = function(index)
    {
        surveySrv.setEditQuestion(index);
    };

    $scope.removeQuestion = function(index)
    {
        $(document).off('click', '#confirmationModal #confirm');
        $('#confirmationModal').modal('show');

        $(document).on('click', '#confirmationModal #confirm', function()
        {
            surveySrv.deleteQuestion(index);

            $scope.$apply();
        });
    };
}]);

service.js

crtPromoSrv.service('surveySrv', function()
{
    var questions = [];
    var editQuestion;

    this.getQuestions = function()
    {
        return questions;
    };

    this.addQuestion = function(question)
    {
        questions.push(question);
    };

    this.setEditQuestion = function(index)
    {
        editQuestion = questions[index];
    };

    this.getEditQuestion = function()
    {
        return editQuestion;
    };

    this.clearEditQuestion = function()
    {
        editQuestion = undefined;
    };

    this.deleteQuestion = function(index)
    {
        questions.splice(index, 1);
        console.log(questions);
    };
});

EDIT: I suspect it could be related to event propagation, as deleting question #2 ends up deleting both #2 and #3 when there are 5 questions in total.

EDIT: Issue resolved, please refer to updated controller.js code.

Answer №1

It seems that there is a recurring issue with adding the 'click' function to your #confirmationModal #confirm button multiple times. Upon calling $scope.deleteQuestion for the first time, the function is added. However, upon subsequent calls, it is added again, resulting in the function being executed twice upon clicking.

To resolve this, a quick fix would involve unbinding the 'click' event prior to adding it again. You can achieve this with:

$('#confirmationModal #confirm').off('click');

A more efficient solution would be to eliminate the reliance on jQuery for these event bindings altogether. Utilizing a straightforward Angular modal directive (such as the one found in the Angular-UI library) would offer a more appropriate approach. By implementing an ng-click on the button, you can avoid encountering this issue entirely.

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

The code encountered a parsing error at 11:1, due to the presence of

I'm having trouble with this code. I've searched for answers but haven't found any solutions. Here is the error message: 11:1 error Parsing error: Unexpected token } ✖ 1 problem (1 error, 0 warnings) npm ERR! code ELIFECYCLE npm ERR! ...

Extracting Parameters using JQuery's load Method

On a webpage, I am attempting to load a jsp page (another.jsp) within a div element while passing parameters. $("#div").load('another.jsp?a=1&b=2'); Despite trying various methods multiple times, I have not been able to get the desired outc ...

Looking for a condensed version of my app script to optimize speed and efficiency

In my script, users input data and run the script by clicking a button. The script then appends the data to two different tabs and clears the data entry tab. However, I encountered an issue where I had to manually hard code each cell for appending, causi ...

What is the best method to determine the accurate height of a window that works across all browsers and platforms?

Is there a way to accurately determine the visible height of the browser window, taking into consideration any floating navigation bars or bottom buttons that may interfere with the actual viewing area? For example, mobile browsers often have floating bar ...

Endless loops: How React JS components can render indefinitely

Every time I try to render a screen with the Bar component, it seems to get stuck in an infinite loop without even passing any data. I tested importing react-chartjs-2 and that worked fine, loading just once. However, the other bar chart keeps rendering co ...

After manipulating the array, Vue fails to render the input fields generated by the v-for directive

After setting the value externally, Vue component won't re-render array items. The state changes but v-for element does not reflect these changes. I have a component that displays items from an array. There are buttons to adjust the array length - &a ...

Verify the form data before triggering the ajax call with just one click

Ensuring that all required areas are completed in a form is crucial. The form needs to be validated properly to either reject the request with a message showing what information is missing, or submit it successfully... The rejection process works well as ...

Check to see if it is possible to click an HTML div

Currently, I am engaged in Selenium and Robot Framework automated testing and in search of a method to automatically locate div tags that are capable of being clicked. The keyword Click Element works well when provided with a specific CSS selector, but ho ...

Enhance the performance of page loading and implement a consistent spinner feature to ensure smooth transitions for users in Next.js version 13

I am currently working on a project using Next.js 13, and I am encountering issues with slow loading times and an unstable spinner when navigating between pages. Specifically, when transitioning from the home page to the /example page, the experience is n ...

Alert: Prop type error encountered - The prop 'open' must be defined in Snackbar component

Recently, I've been implementing jest snapshot tests into my application. The main focus is on the LoginForm component. render() { return ( ... <DynamicSnack dialogOpen={this.props.dialogOpen} snackOpen={this.props.sna ...

Perform an HTTP GET request to a RESTful service with specified parameters using Angular 2

I'm currently facing an issue while attempting to create a GET request to the YouTube Web API. I'm struggling with passing parameters through the http.get function and have confirmed the request is being sent using Fiddler. However, I keep receiv ...

Is there a method to access a website, trigger JavaScript functions, and subsequently retrieve the HTML content using PHP?

I am currently exploring options to access a webpage, execute JavaScript functions on it (thus altering the HTML content), and eventually save the modified version of the page. I'm uncertain if this approach is feasible, and if not, are there alternat ...

The method .makePerspective() in THREE.Matrix4 has been updated with a new signature. Make sure to refer to the documentation for more information

Attempting to run a functional three.js code using release 119 of three.js (instead of r79) has resulted in an error being thrown by the previously functioning code: THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check ...

Comparing AngularJS: The difference between ng-click function and directive

I'm facing a dilemma in choosing the best method for triggering an alert when buttons are clicked. There are two methods I've come across, and I need help determining which one is the preferred practice. Can you provide insights into why one meth ...

The data type 'unknown' cannot be assigned to the type 'any[]', 'Iterable<any>', or (Iterable<any> & any[])

I have been working on creating a custom search filter in my Angular project, and it was functioning properly. However, I encountered an error in my Visual Studio Code. In my previous project, everything was working fine until I updated my CLI, which resul ...

Insert a parameter or substitute the existing value if detected

Trying to create a JavaScript regex that searches for a parameter in a URL and replaces its value if found. If the parameter is not found, it should be added to the URL. Here are a couple of scenarios: http://www.domain.com/?paramZ=123456 https://www.dom ...

Capture data from Ajax requests and store them in PHP variables

When setting up a DDBB Insert using $.ajax, I encountered an issue. $(document).on('click','.submitMessage', function(){ content=$('textarea').val(); img=$('#messageImg').val(); stdMsg=$('.ms_stdMsg ...

Is there a way to customize event property setters such as event.pageX in JavaScript?

Is there a way to bypass event.pageX and event.pageY for all events? This is because IE10+ has a known bug where it sometimes returns floating point positions instead of integers for pageX/Y. ...

What is the reason for the failure of the jQuery code to disable the submit button in the following snippet?

I am working on a feature to disable the submit button in a form when the username, email, password fields are empty. When all of them are filled, I want to enable the submit button. However, the current code is not disabling the submit button as expected. ...

Error message encountered in AngularJS when trying to send Fullcalendar: TypeError - Cannot access property '__id' of an undefined object

Recently, I integrated angular-ui-calendar into my website. Within the controller, I implemented the following: define(['underscore'], function (_) { "use strict"; var SearchController = function ($scope, $location, OrdersService, U ...