How to delete the last item of an array in AngularJS using scope

In my Angular controller, I have an array and a method for deleting objects.

function($scope, $http){
    $scope.arrayOfObjects = [];
    $scope.remove = function(obj){
        var i = $scope.arrayOfObjects.indexOf(obj);
        if( i > -1 ){
            $scope.arrayOfObjects.splice(i, 1);
        }
    }
// Additional code here
}

HTML

<a href ng-repeat="(key, obj) in arrayOfObjects track by $index">{{obj.id}}

<button type="button" role="button" class="btn btn-default" ng-click="remove(obj)">
   <i class="fa fa-trash"></i>
   <span>Delete</span>
</button>

</a>

Everything works fine when deleting objects except for the last one. When the user tries to delete the last object, the page redirects to localhost:3000/# which results in a blank page. Has anyone else experienced this issue?

Answer №1

While some of the other responses are focused on addressing your issue with the link/redirect problem, which can be resolved by avoiding having additional clickable elements inside an anchor tag, the main issue lies in using incorrect syntax for iterating through array objects.

To properly iterate over an array, you should use this format:

ng-repeat="obj in arrayOfObjects"

The syntax you are currently using is meant for iterating over the properties of a single object. In this case, key and value are the arguments passed to your repeater function.

ng-repeat="(key, value) in object"

It seems like what you actually need is something along these lines:

<div ng-repeat="obj in arrayOfObjects">
  {{obj.id}}
  <button ng-click="remove(obj)">Delete</button>
</div>

Check out the codepen example here

Answer №2

If you need to filter and return specific items back to the original scope, you can achieve this using the 'filter' function as shown below:

        $scope.remove = function (objs) {
            $scope.objs = objs.filter(function (obj) {
               //Specify the condition to remove unwanted items
               return obj;
            });
        };

Here is the HTML component for triggering the removal:

    <button class="btn btn-danger btn-block" ng-click="remove(objs)">Delete</button>

Answer №3

To remove the last element from an array in AngularJS, you can use the pop() method which not only removes the element but also returns it. An example of this would be $scope.arrayOfObjects.pop()

angular.module('app', [])
.controller('mycontroller', function($scope) {
  $scope.arrayOfObjects = [{ id: 1 }, { id: 2 }, { id: 3 }]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="mycontroller">
  <button ng-click="arrayOfObjects.pop()">remove in inline</button>
  <ul>
    <li ng-repeat="myobj in arrayOfObjects">{{myobj.id}}</li>
  </ul>
</div>

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

Encountering issue - SCRIPT5022: Error parsing message from server in Sys.WebForms.PageRequestManagerParserErrorException

I'm in need of assistance. I've developed a web application in .Net 3.5 that utilizes asp.net Master page, update panel, and server controls. The asp.net page created with the Master page includes an update panel that contains other server contro ...

Deeply nested .map function to update state value

The current state value const [settings, setSettings] = useContext(SettingsContext) Utilizing the .map method on the settings state {settings[categoryIndex]?.config?.map((item: ConfigItem, index: number) => ...

Incorporate the ng2-ace library into a newly generated Angular-CLI (Angular2) project with the help of SystemJS

After setting up my angular2 project using the latest angular-cli tool, I decided to integrate the ace editor with the help of the ng2-ace library. My goal was to implement this in a clean manner using SystemJS as the module loader. I started by running ...

Having trouble passing input values from the view to the controller in Angular?

Having an issue with sending data to the controller via my view. Below is a snippet of the code: <form ng-submit="submitMessage()"> <div class="form-group"> <input type="number" class="form-control input ...

Unable to modify the value of an object variable generated from a query in JavaScript, ExpressJS, and MongoDB

Here is the code snippet I've been working on: let addSubmissions = await Submission.find({"type": "add-information"}, (err) => { if(err) { console.log(err) req.flash('error', 'No "add submissions" were found&apo ...

processing an array using ajax form submission

Trying to manage an array that is returned from a PHP file after submitting form data. The value of the data after form submission is = ARRAY but I am unable to use this array in any way. Any suggestions on how to handle this array? Javascript: $(&apo ...

The Upstash Redis scan operation

Attempting to utilize the @upstash/redis node client library for Node.js (available at https://www.npmjs.com/package/@upstash/redis), I am facing challenges in executing the scan command, which should be supported based on the documentation. Specifically, ...

Guide to automatically updating a table with AJAX requests

My task involves utilizing AJAX to request a random string consisting of 10 numbers from an asp page. The numbers must be delimited by "||" and displayed in a table format. The table is designed to showcase only the top 10 results, with each new row addin ...

Are you utilizing Google Chrome extensions for importing and exporting JSON files?

Currently, I am in the process of developing a Google Chrome extension and I have a question regarding its capabilities. Is it possible for the extension to generate JSON files for users to download (export) as well as implementing a button that allows use ...

When a td element is clicked, the Textbox will also be clicked

Similar Question: Dealing with jQuery on() when clicking a div but not its child $(oTrPlanning).prev().children('td').each(function () { this.onclick = setCountClick; }); When a TD element is clicked, the function setCountClick() i ...

Is there a solution for the continuous automatic incrementing of the jQuery UI spinner that occurs when I right-click on it?

Only Linux and Mac OS users are facing this particular issue, indicating a potential bug with the jQuery spinner. The bug also affects the spinner located at the following link: https://jqueryui.com/spinner/ <input class="spinner"/> $(".spinner"). ...

Testing XMLHttpRequest with Jasmine: A Complete Guide

Is there a way to test the onreadystatechange function on XMLHttpRequest or pure JavaScript AJAX without using jQuery? I need to do this because I'm working on a Firefox extension. It seems like I may have to use spies, but I'm having trouble bec ...

Display the number in a formatted manner without displaying any zeros in the decimal part

Can you help me with a decimal number display issue I am having? <nested:text property="product.price" maxlength="5" onclick="javascript:validatePriceValue(this);"/> number displayed as 44 44.00 I want to use J ...

Inquiries prior to projecting rays

As I delve into the world of Interaction with Three.js, several questions arise in my mind. 1) Can you shed some light on what exactly Viewport Coordinates are? 2) In what ways do they differ from client Coordinates? 3) How did we come up with this form ...

Is there a way to retrieve JSON data from a specific URL and assign it to a constant variable in a React application?

I am exploring react-table and still getting the hang of using react. Currently, in the provided code snippet, a local JSON file (MOCK_DATA.json) is being passed into the const data. I want to swap out the local JSON with data fetched from a URL. How can ...

Ways to enhance multiple ng-repeats efficiently with css grid

Looking to create a CSS grid table with 5 columns and an undetermined number of rows. The goal is to display a pop-up element when an element in the first column is clicked, covering columns 2 through 5. This ensures that only the first column remains visi ...

Tips for avoiding Netlify's error treatment of warnings due to process.env.CI being set to true

Recently, I encountered an issue with deploying new projects on Netlify. After reviewing the logs, I noticed a message that had never appeared during previous successful deployments: The build failed while treating warnings as errors due to process.env.CI ...

displaying HTML content in an Angular controller

Can someone please guide me in the right direction? I am working on a web app where users need to click a button as quickly as possible to get a score. The design requires that this score be displayed in double digits, for example, 9 would be displayed as ...

Extracting information from a Weather API and sharing it on Twitter

Can anyone help me troubleshoot my Twitter bot setup for tweeting out city temperatures? I attempted switching to a different API, but nothing seems to be resolving the issue. console.log('initiating twitter bot...') var Twit = require('t ...

I'm facing an issue with SSRProvider in my NextJs application

My application is developed using NextJs and Typescript, utilizing the react-bootstrap library for creating components. I am facing an issue where I keep receiving an error message stating that When server rendering, you must wrap your application in an &l ...