AngularJS not compatible with Splice functionality

Currently, I am working on a form for an Items list that allows users to add, edit, and delete items. While the add and edit functionalities are working correctly, I am facing some issues with the delete functionality.

Below is a snippet of my code that includes the delete button:

      <!-- Added Items Stage -->
      <div ng-repeat-start="item in items" ng-form="editItemForm" class="row">
        <div class="col">
          <input type="text" name="description" ng-model="item.description" placeholder="description" required>
        </div>
        <div class="col">
          <input type="number" name="quantity" pattern="\d*" ng-model="item.quantity" placeholder="quantity" required>
        </div>
        <div class="col">
          <input type="text" name="price" ng-model="item.price" placeholder="price" required>
        </div>
        <div class="col">
          <select name="taxType" ng-model="item.taxType" required>
            <option value="ZR">ZR</option>
            <option value="SR">SR</option>
          </select>
        </div>
        <div class="col col-20" ng-bind="(item.quantity&&item.price)?((item.quantity*item.price) | currency:''):'0.00'"></div>
        <div class="col col-10">
          <button type="button" class="button button-assertive button-clear icon ion-close-circled" ng-click="deleteItem(item)"></button>
        </div>
      </div>

      <hr ng-repeat-end>

Additionally, here is the function I am using to delete an item:

$scope.deleteItem = function(item) {
    $scope.items.splice($scope.items.indexOf(item), 1);
};

I have tried using `$index` and the `delete` method instead of `splice`, but I am still facing issues. Any assistance would be greatly appreciated. Thank you.

You can view a demo here.

Note: It seems like the item is removed, but the HTML is not being updated accordingly.

Answer №1

There are instances where Angular may not immediately recognize changes made to the model. In such cases, you can manually trigger an update by encapsulating your function within a $timeout block without any delay:

$scope.removeItem = function(item) {
    $timeout(function () {
        $scope.items.splice($scope.items.indexOf(item), 1);
    });
};

Remember to include the $timeout service in your controller's dependencies.

Answer №2

It seems that the issue lies within the ng-form attribute of your repeater.

If you remove it, everything should function correctly.

var nameApp = angular.module('starter', ['ionic', 'ngMessages']);

nameApp.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
    .state('auth', {
      url: '/auth',
      templateUrl: 'auth.html',
    })
    .state('home', {
      url: '/home',
      templateUrl: 'home.html',
      controller: 'HomeCtrl'
    });

  $urlRouterProvider.otherwise("/auth");

});


nameApp.directive('isolateForm', [function() {
  return {
    restrict: 'A',
    require: '?form',
    link: function(scope, elm, attrs, ctrl) {
      if (!ctrl) {
        return;
      }

      // Do a copy of the controller
      var ctrlCopy = {};
      angular.copy(ctrl, ctrlCopy);

      // Get the parent of the form
      var parent = elm.parent().controller('form');
      // Remove parent link to the controller
      parent.$removeControl(ctrl);

      // Replace form controller with a "isolated form"
      var isolatedFormCtrl = {
        $setValidity: function(validationToken, isValid, control) {
          ctrlCopy.$setValidity(validationToken, isValid, control);
          parent.$setValidity(validationToken, true, ctrl);
        },
        $setDirty: function() {
          elm.removeClass('ng-pristine').addClass('ng-dirty');
          ctrl.$dirty = true;
          ctrl.$pristine = false;
        },
      };
      angular.extend(ctrl, isolatedFormCtrl);
    }
  };
}]);



nameApp.controller('AuthCtrl', function($scope, $state) {

  $scope.newItem = {
    description: undefined,
    quantity: undefined,
    price: undefined,
    taxType: undefined
  };

  $scope.items = [];

  $scope.addItem = function() {
    console.log({
      description: $scope.newItem.description,
      quantity: $scope.newItem.quantity,
      price: $scope.newItem.price,
      taxType: $scope.newItem.taxType
    });

    $scope.items.push({
      description: $scope.newItem.description,
      quantity: $scope.newItem.quantity,
      price: $scope.newItem.price,
      taxType: $scope.newItem.taxType
    });

    console.log($scope.items);

    $scope.newItem.description = undefined;
    $scope.newItem.quantity = undefined;
    $scope.newItem.price = undefined;
    $scope.newItem.taxType = "SR";

  };

  $scope.deleteItem = function(item) {
    $scope.items.splice($scope.items.indexOf(item), 1);
  };

  $scope.authorization = {
    referenceNo: '',
  };

  $scope.signIn = function(form) {
    if (form.$valid) {
      $state.go('home');
    }
  };

});

nameApp.controller('HomeCtrl', function($scope) {

});
.error-container {
  margin: 5px 0;
}

.error-container:last-child {
    margin: 5px 0 0;
}

.error {
  padding: 10px 16px;
  font-family: "Arial Black", Gadget, sans-serif;
  font-size: 11px;
  text-transform: uppercase;
  color: #555;
  vertical-align: middle;
}

.error i {
  font-size: 24px;
  color: #B83E2C;  
  vertical-align: middle;
}

.last-error-container > .error {
  padding: 10px 16px 0;
}

.has-errors {
  border-bottom: 3px solid #B83E2C;
}

.no-errors {
  border-bottom: 3px solid green;
}
<html ng-app="starter">
 
  <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet"/>
  <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-messages.js"></script>  
   ....(remaining code is unchanged)

Answer №3

Encountered a similar issue of "Splice not working". I managed to find a solution that may be of help to others facing the same problem.

If you are working with objects, keep in mind that 'indexOf' works for arrays and not for objects inside an array. You can use the following code snippet to identify the index and handle this scenario:

$scope.removeReport = function(report) {
    var index = $scope.contact.reports.map(function(r) { return r.id;}).indexOf(report.id);
        if (index >= 0) {
          $scope.contact.reports.splice(index, 1);
        }
}

Answer №4

Replace Item with Index

<button type="button" class="button button-assertive button-clear icon ion-close-circled" ng-click="deleteIndex($index)"></button>

Update Controller as well

$scope.deleteIndex = function(index) {
    $scope.items.splice(index, 1);
};

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

Trigger a pop-up alert box when the jQuery event $(document).ready is fired within a Smarty template

I'm currently attempting to make a popup message display when the document is fully loaded. Although I have successfully integrated Google Maps on another page, this task seems to be more challenging. Below is the code snippet: <html> < ...

How can I use HTML and jQuery to send a button click event to a .py file using AJAX and cgi in web development?

I have encountered a challenge with posting data from button clicks on an HTML page to Python CGI for insertion into a PostgreSQL database. My script seems to be struggling with this task. Here is the structure of my HTML, ajax, and javascript: '&ap ...

Shadow and Quality Issues with SVG Images

I have designed a unique SVG image with intricate details and a decorative frame, enhanced with shadowing effects. Unfortunately, after importing this SVG into a react-native application using the react-native-svg library, I noticed that the shadow around ...

Error: The Rollup module is unable to locate the 'jquery' file

I've been facing an issue while trying to bundle a vuejs single file component using rollup. The error message that keeps popping up is Module not found: Error: Can't resolve 'jquery'. Despite spending countless hours on this problem, I ...

"Unlocking the Dialog Box: A Step-by-Step Guide to Programatically Opening Material UI Dialog

Typically, Material UI's Dialog is used as shown below, following the documentation: export default function AlertDialog() { const [open, setOpen] = React.useState(false); const handleClickOpen = () => setOpen(true); const handleClose = () =& ...

Trouble with the fetch request on the express root router when trying to connect with React

I am facing an issue while attempting to call the root router ('/') of Express using fetch API in React in production mode but it seems to be not working as expected. In my setup, I am utilizing a common server for serving static React views and ...

Can someone show me how to make an ajax request from a panel within a Firefox extension?

Seeking guidance on utilizing panels in the Firefox addon. How can I initiate an ajax request from a panel? Also, what is the best way to debug a panel since Firebug does not seem to recognize it? ...

Is there a way to efficiently clear the Express session for all users without the need to restart the application?

During my development of REST services using the nodejs express framework, I encountered an issue with storing user-specific data in sessions. I utilized the user's ID as a key to identify the user's data. The following code snippet demonstrates ...

Creating a heading transition that moves from the bottom to the top with CSS

I am looking to add an animation effect to the H1 element in my program. I want it to smoothly appear from the bottom hidden position using a CSS transition when the page loads. How can I achieve this? Additionally, I need the height of the bounding elemen ...

Save the model with the updated value

Currently, I am working on a piece of code that involves the following: <select ng-model="rule.platforms" ng-options="platform for platform in platforms" name="platform" multiple required> <option value="">-- platform --</option& ...

What is the best way to access the parent document of a Firestore collectionGroup query?

I'm currently working on accessing the parent documents of all subcollection queries in my database structure. The setup I am aiming for is something like this: /production/id/position/id/positionhistory While I have successfully retrieved all the d ...

Challenges encountered with input outcomes

I am facing an issue with input results. I have a button that triggers a function to check for empty input fields. However, when I click the button, it always falls into the last if statement and displays as if the fields are not empty. I have already att ...

Can a post request be sent in Node/Express using just HTML and server-side JavaScript (Node.js)?

Can a post request be made in Node/Express using only HTML and Server-side Javascript? (HTML) <form action="/submit-test" method="post"> <input type="text" name="id"> <button type="submit">Submit</button> </form> (N ...

The jquery layout is experiencing issues when being loaded within the ui-view

I encountered an issue with my layout created using JQuery layout. Everything works perfectly in a normal index file, but when I try to load it through the ui-view directory, it fails to load. Can someone provide assistance? My index.html <html ng-app ...

Display a component by selecting a hyperlink in React

Currently working on a story in my storytelling, which might not be too important for the question I have. What I am trying to accomplish is creating a scenario where there is an anchor tag that, once clicked, triggers the opening of a dialog box or modal ...

Discover the initial two instances of a specific element within a collection of javascript objects

Within my javascript arraylist, I am currently storing the following elements: list = [ {header: "header1", code: ""}, {label: "label1", price: 10}, {header: "header2", code: ""}, {header: "header3", code: ""}, {header: "header4", code: ""} ] My que ...

Can a JavaScript function spontaneously run without being called upon?

<a onclick="determineCountry(data)" class="installbtn">Install</a> My goal is to have the user redirected to one of three sites based on their location when they click the button above. However, there seems to be an issue with the script below ...

Sending AJAX request within a Twitter Bootstrap modal in Symfony2

After exhausting countless Google and StackOverflow search results, I have come to the conclusion that seeking help is my best option. I am currently developing a Symfony2 application. In every view of my app, I have integrated a Twitter Bootstrap modal e ...

Transferring a variable between a JavaScript function and a Java class

Currently, I am working with STS and building an application that includes HTML files and JavaScript. Within this file, there is a function that configures variables. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www ...

Issues with React JS and JavaScript filtering functionality not working correctly

I've been working on implementing a filter feature for a website, using an HTML range slider. However, I've encountered an issue where the values only update correctly when decreasing. For example, if I set the slider to $500, only products that ...