Is the reordering of items in an Angular JS array causing a malfunction with the first item

It appears that there may be a syntax error present in my code.

Within my controller, I have a set of 4 functions: adding a new item, deleting the current item, moving an item backward (up) in the array, and moving an item forward (down) in the array.

All of these functions are functional, except when attempting to move the first item down in the array.

vm.maxChoices = 6;

vm.addNewChoice = function(arr) {
  var newItemNo = arr.length + 1;
  arr.push({
    'id': 'choice' + newItemNo
  });
};

vm.deleteChoice = function(arr, index) {
  arr.splice(index, index);
};

vm.moveUpChoice = function(arr, index) {
  var currItem = index;
  if (currItem>0) {
    arr.splice(currItem-1,0, arr.splice(currItem, currItem)[0]);
  }
};

vm.moveDownChoice = function(arr, index) {
  var currItem = index;
  var newPosition = index+1;
  if (currItem < arr.length) {
    arr.splice(newPosition,0, arr.splice(currItem, currItem)[0]);
  }
};

vm.showAddChoice = function(choice,arr) {
  return arr.length !== vm.maxChoices;
};

My question is, what mistake have I made with the moveDownChoice function?

You can see a working example here: http://plnkr.co/edit/WPdnmYbDSXC0LsbeMduM?p=preview

Feel free to create 3 or 4 rows, input data into the fields to observe the movement. You will notice that you can move #2 to #3 etc., but trying to move the first item down results in creating a NEW item instead of moving it to #2.

Answer №1

The functions for moving choices up and down, moveUpChoice and moveDownChoice, are both incorrect. They do not function as expected.

The .splice() function requires 3 parameters: position, numToRemove, and itemsToInsert. It returns an array of the removed items.

In your code, you are instructing it to go to the item's position, remove that number of items from that position, and then insert the first item at the new position. This results in removing more data than you actually add in some instances. For example, using the up arrow will cause the second-to-last item to disappear from the array.

Instead, consider trying arr.splice(newPosition, 0, arr.splice(currItem, 1)[0]);

Answer №2

There is a common bug in both the moveUpChoice and moveDownChoice functions that you need to address.

arr.splice(currItem, currItem)[0]

To fix this issue, make sure to change it to:

arr.splice(currItem, 1)[0]

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

Getting a dictionary object in JSON format - a beginner's guide

I just started delving into json. To retrieve the title object, I can use this code: json_data = results['local_results'] for i in json_data: if "title" in i: title = i["title"] Now, how do I go about accessing the latitude object wi ...

What is the reason behind lightbox not disabling scrolling?

While using the default lightbox2 CSS and JavaScript, everything is functioning correctly except for an issue on Safari mobile. When I click an image and the lightbox opens, swiping to the left reveals blank white space despite having overflow-x set to hid ...

Trouble with mobile compatibility for .json file content population in HTML elements script

Check out THIS amazing page where I have a series of placeholders for phone numbers in the format: 07xxxxxxxx. By simply clicking the green button "VEZI TELEFON", each placeholder in the green boxes gets replaced with a real phone number from a JSON file u ...

Showcasing top performers via JavaScript tabs

I have two tabs on my webpage: "Overall Leaderboard" and "Weekly Leaderboard". Each tab displays a leaderboard with different scores. When I click on the "Overall Leaderboard" tab, it shows a leaderboard with specific scores. Now, my question is how can ...

Flipping an array in C Programming

I've hit a roadblock with some code that I've been working on. The task at hand is to collect N inputs using the argc and argv[] parameters. These N inputs will then prompt the user to enter an equal number of sentences. For each sentence, my obj ...

Creating a unique Angular JS / Material / Datatables application - Proper script loading sequence required based on page context

My top two declarations placed above the closing body tag. When used in a material dropdown page, the current order of these scripts works fine. However, when I switch to my datatables page (which is a separate page), I need to swap the order of the two s ...

Enforcement of Typescript Field Type Lax During Assignment

My current issue involves a constructor that is supposed to set the value of _device. The field is specifically designed to be of type number, and the constructor parameter is also expected to be of type number. However, when a parameter of type string is ...

Creating an HTML table using an array of objects

I'm currently working on creating a function that will generate an HTML table from an array of objects. The array provided below is what I need to convert into a table. let units = [ { 'code': 'COMP2110', &apos ...

Resizing Bootstrap Modal using React with a Personalized Dimension

Is there a way to manually set the width of Bootstrap's Modal React component on my website? I want to be able to define the width in pixels, and if possible, use a const object in the .jsx file for CSS. If not, I can resort to using a .css file. Be ...

Encountering an EJS error stating SyntaxError: a closing parenthesis is missing after the argument list in the file path C:Userscomputer pointDesktopproject2viewshome.ejs

Struggling to retrieve data from app.js through ejs and encountering an error. Pursuing a degree in Computer Science <%- include('header'); -%> <h1><%= foo%></h1> <p class = "home-content">It is a fact that readers ...

Is it possible to convert an array into an object?

I'm attempting to restructure an array of objects into a new object where the label property serves as the key for multiple arrays containing objects with that same label. Check out this JSBin function I created to map the array, but I'm unsure ...

Create a function that will repeatedly call itself at specified intervals, increment a variable, and update the class values of elements with an id matching the current value of the

I'm attempting to create a setup that cycles through different images <div id="img_box" class="shadow" onload="imgCycle(1)";> <img id="1" class='opaque imgbox selected' src="media/img ...

What is the process for adding information to a MongoDB collection?

Working with NodeJS using Mongoose, I have defined two tables in db.js: const mongoose = require('mongoose') const UserSchema = new mongoose.Schema( { username: { type: String, required: true, unique: true }, email: { type ...

Dart Manual Injection Guide

What is the recommended method for manually injecting an instance in Angular Dart? Can you demonstrate with an example similar to the one below in AngularJS: var myInjector = angular.injector(["ng"]); var $http = myInjector.get("$http"); ...

Organizing AngularJS Components: Finding the Right Spot for the "Model" within Your Directory Structure

When it comes to AngularJS, it adheres to the MVC pattern (or more accurately MV*). Typically, we create distinct directories for each layer. For instance, controller JS files are usually placed in a directory called "controllers", and views are commonly s ...

Exploring the View-Model declaration in Knockout.js: Unveiling two distinct approaches

For my latest project, I am utilizing Knockout.js to create a dynamic client application with numerous knockout.js ViewModels. During development, I came across two distinct methods of creating these ViewModels. First method: function AppViewModel() { thi ...

the click event fails to trigger when the id or class is modified

Hey there, I'm new to working with jquery and I've encountered a problem. Here's the code snippet: http://jsfiddle.net/8guzD/ $('#test.off').click(function(){ $(this).removeClass('off').addClass('on'); }) ...

Timing measurements in JavaScript: comparing Date.now with process.hrtime

I need to regularly calculate the time difference between specific time intervals. When it comes to performance, which method is more efficient: Date.now or process.hrtime? C:\Windows\system32>node > process.hrtime() [ 70350, 524700467 ] ...

A guide on verifying the creation of an Angular service through Jasmine testing

In front of me is a code snippet that serves as a branch from ng-wrap, taking inspiration from this particular article. Essentially, it establishes an angular service for global variables introduced by external libraries to align with the concept of depend ...

Error occurs when trying to create or delete a folder in Express.js

Implement Folder Creation Code in index.js let companydir = './views/campaigns/' + companyname; if(!fs.existsSync(companydir, { recursive: true })) { fs.mkdirSync(companydir, { recursive: true }); } var dir = companydir + &apo ...