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

trapping errors in AngularJS

Recently, I was looking into an angular-fullstack application and stumbled upon the following code snippet: catch( function(err) { err = err.data; $scope.errors = {}; // Update form field validity based on mongoose errors angular. ...

Exploring the depths of object properties with Angular, JavaScript, and TypeScript: A recursive journey

Let's consider an object that looks like this: const person = { id: 1, name: 'Emily', age: 28, family: { mother: { id: 101, name: 'Diana', age: 55 }, fathe ...

Typing the url in the address bar when using Angular's ui-router

Two distinct states are present: .state('test', { url: '/test', templateUrl: 'js/angular/views/test.html', controller: 'UserController', }) .state('test.list', { url: ' ...

The frequency of the geolocation watchPosition in Cordova exceeds the set options

In my ionic/angularjs application, I am utilizing the geolocation plugin from this link: https://github.com/apache/cordova-plugin-geolocation Following the documentation, I have set up the watch configuration as shown below: var watchOptions = { freq ...

An Ajax call navigates to the index.html page

Could you please assist with an issue I am facing? I have written the code below to make an ajax request to a specific link. However, instead of executing the ajax call using a POST request, the page is being redirected to index.html with the link in the ...

Returning to the previous page is done by navigating back using the previous URL in Next.js

Recently, I encountered a situation where I had implemented filters on a webpage. Upon applying the filters, the URL of the page would change and additional query strings would be appended to the end. This caused an issue when navigating back using the b ...

Grails: Javascript function for updating the image source is unresponsive

I have a situation where I need to change the src of an img based on a certain condition. The condition is returning true as expected, as confirmed by an alert() that I added previously. However, the function responsible for changing the src of the img and ...

What could be the reason for TypeScript being unable to recognize my function?

In my code, I have a Listener set up within an onInit method: google.maps.event.addListener(this.map, 'click', function(event) { console.log(event.latLng); var lt = event.latLng.lat; var ln = event.latLng.lng; co ...

The event listener $(window).on('popstate') does not function properly in Internet Explorer

$window 'popstate' event is not functioning properly in IE when using the browser back button. Here is the code snippet used to remove certain modal classes when navigating back. $(window).on('popstate', function(event) { event.pre ...

How do I use props to enable and conceal elements like lists, buttons, and images?

Check out this unique component: <ReusedHeader H1headerGray="text here... " H2headerRed="text2 here ! " pheader="p1" getStarted="button text1" hrefab="button url 1" whatWeDo="button text ...

Running a script within an Ajax-rendered form using remote functionality in a Ruby on Rails

After clicking the following button, my form is rendered: = link_to 'New Note', new_note_path, :class => "btn btn-primary new-note-button", :type => "button", :id => "new-link", remote: true The form is rendered using the script below ...

Demonstrate how to pass a newline character from Ruby on Rails to JavaScript

I am working with a .js.erb file that is activated by a JavaScript function. Within this js.erb file, I have the following snippet of code: event = <%=raw @event.to_json %> $('#preview-event-body').html(event.body); The value of event.bo ...

alerting the user of any modifications made to a table within the database

In my current Spring project, I am seeking the optimal solution to improve system performance. Should I implement a solution using Javascript or create a custom method in Java? ...

Tips for extracting Stripe response post payment using a client-side-only integration

My current component handles sending a payment order to my stripe account on the client-side. Everything seems to be working fine, but I'm struggling to find a way to retrieve the response or token from stripe containing the order details, which I nee ...

Setting up ngModel with information - AngularJS Bootstrap bs-select

Currently, I am managing a website that enables users to create profiles and share activities via a feed. To organize all the created profiles, I have integrated ng-grid into the system. Additionally, I have implemented two buttons that allow users to eith ...

Ways to determine the specific content type within req.body?

Based on the information found at https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, it is stated that the body of a request can be one of the following types: ArrayBuffer Blob formData JSON text I am wondering if there is a way ...

Direct your attention to alternative data sources following the selection of an item in the typeahead search feature

Having some trouble with angular-ui bootstrap: I am using 2 input elements: <input type="text" ng-model="selected" uib-typeahead="state for state in states | filter:$viewValue | limitTo:8" typeahead-on-select="focusSuccessive($item, $model, $label, $ev ...

Modifying radio inputs to update when a state variable is altered in react.js

In my HTML, I have a div that includes 4 radio inputs, and another div with an onClick event that increments a counter. Every time I click on the div, I want the radio inputs to reload so that no input is selected. Below is the code snippet: 'use clie ...

Display the names of files depending on the selection made in the drop-down menu

In order to utilize a value from a select box for a PHP function later on the page, I am seeking assistance. Within my index.php file, there is a standard select drop down containing folder names as values and options. After selecting a folder, I aim to e ...

Are you facing difficulties while trying to utilize useContext in your React application?

I have a basic React application where I need to implement useContext. (by the way, I am using Vite + React) Below is the code for my Context.jsx file: import React, {useContext} from 'react'; const emailContext = React.createContext(); expor ...