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

Configuring a Meteor.js application requires defining variable scopes for templates in order to manage

Is there a way to define a variable that is limited in scope to a specific template? I want this variable to be accessible by multiple helpers within the template, but not outside of it. For example, how can the game variable be shared between two templat ...

Looking for assistance with implementing a jQuery function for an onClick event on

I've been diving into learning jquery and managed to create a basic checkbox feature with a function that allows you to set all options as read-only by checking the "None of the above" button. <html> <body> <form id="diagnos ...

Remove elements from an array based on the indices provided in a separate array

1) Define the array a = [a,b,c,d,e,f,g,h,i,j]; using JavaScript. 2) Input an array 'b' containing 5 numbers using html tags. This will be referred to as the 'b' array. 3) Insert elements into array 'b' ensuring they are alwa ...

Ensure that you patiently wait for the axios method to finish execution before moving on to the

I am currently learning vue.js and struggling with the concept of promises. I need to initialize a variable with data from an API call, but I want to ensure that the Axios call is generic: { data: { list: [], }, methods: { ShowList: function ...

Uploading images in React JS by allowing users to paste images

Currently working on a chat application using React JS and I'm looking to enable image uploading when an image is pasted into the chatbox. How can I make this happen? Essentially, I am in need of: An event that will activate upon performing the "Pas ...

Parsing improperly formatted JSON from an HTTP GET request can be done using either AngularJS or JQuery

Trying to decipher a poorly formatted JSON response from a remote server that looks something like this: //[ {},{} ] In my AngularJS code: $http.get('http://www.example.com/badjson') .success(function(data) { console.log(data); }) ...

Using CloudantDB and NodeJS to retrieve data based on specific id

I recently set up a NodeJS cloudantDB web starter on bluemix. After that, I managed to successfully retrieve data from cloudantDB using an API, but it returned all the data available. Here's an excerpt from my JavaScript file: JavaScript file: app.g ...

When certain triggers are activated, a hidden textbox revealed through javascript is made visible

After changing a dropdown value (from ddlSource) and hiding some text boxes using JavaScript, everything works fine. However, when the user enters a certain value in another textbox triggering an AJAX call to populate some labels, upon form reload, the hid ...

Click twice on the editable AngularJS table to wrap each item

As a new learner of Angularjs, I found an existing code example and decided to customize it. My goal was to enable double-click editing for each li item. However, after adding one more li, the functionality did not work as expected. <li ng-dblclick="st ...

Instructions for utilizing lodash or JavaScript to apply a filter to an object

Received this object from the Server: var data = { test1: { documents: [] }, test2: { documents: [{ vId: 'sdfas23', TypeId: '81', isDeleted: false }], answer: true }, test3: { documents: ...

When utilizing the http.post method, the req.body is not being populated as expected

I am puzzled by the fact that the req.body appears to be empty... app.js utilizes the body-parser middleware() var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/in ...

I am looking to implement a feature that will disable unchecked checkboxes based on certain conditions in a

Upon selection of an option from a dataset, an API call is triggered. The API response includes an object with a nested array, whose values are listed as checkboxes. Additionally, the API returns a key named choose(const name primaryMax) indicating the max ...

Troubleshooting: Directives in Angular 4 not recognizing RegEx patterns

I have developed a directive that validates the input in a text field, allowing users to enter numbers, dots, and commas. However, the validator only seems to work for numbers and not for commas and dots. import { Directive, ElementRef, HostListener } fro ...

Error: Required variable missing in AJAX Post request

When making an ajax call, I use the following code: o.open("POST",q,true); o.setRequestHeader("Content-type","application/x-www-form-urlencoded"); o.setRequestHeader("Content-length",p.length); o.setRequestHeader("Connection","close"); Here, q represent ...

"Executing a query on Angular Firestore using the where clause fetches all documents from the

I am encountering a perplexing issue with my angular app that is connected to Firestore. Despite following the documentation closely, when I query for documents in a collection based on a specific condition, the array returned contains every single documen ...

Determine if a file input is linked in React.js Material UI

Currently, I am working with a Material UI <TextField /> component that has a type=file prop to allow file attachments. My goal is to trigger an event when a file is attached to this TextField. However, my search results only provided JQuery soluti ...

The HttpParams are reluctant to be established

Working with Angular 8, I am attempting to assign an HttpParam using the provided code snippet and observing the outcome on the final line. let newParams = new HttpParams(); newParams.set('ordering', 'name'); console.log('getting: ...

Looking to update the key name in a script that produces a list sorted in ascending order

I have been working on code that iterates through a flat json document and organizes the items into a hierarchical structure based on their level and position. Everything is functioning correctly, but I now need to change the name of the child elements to ...

Error: The function .default.auth.signout is not recognized in the REACT and Firebase environment

I've come across several error questions on StackOverflow, but most remain unanswered. The ones that are answered don't seem to solve my issue. I need help debugging this particular error. In my REACT project using Firebase, I'm working on ...

Unexpected lag causing delays in jQuery animations

I am attempting to implement a "hover" effect using jQuery. Everything seems to be working fine, except for a strange delay that occurs only the first time the complete callback is triggered - oddly enough, this is the only instance where it reaches the pr ...