Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the length of the array and add a default object. Conversely, if the number is decreased, I should remove the last object from the array. Below is the code snippet I have been using:

// HTML
<input type="number" class="form-control" min="0" max="12" ng-click ="topEntriesSelectOffense()" ng-value="page.offense.topRow.length">

// Controller
$scope.topEntriesSelectOffense = function () {
    // Add new object when the number increases
    $scope.page.offense.topRow.push({
        "1": {
            "firstName": "FirstName",
            "lastName": "LastName",
            "headshot": "file/path"
        },
        "2": {
            "firstName": "FirstName",
            "lastName": "LastName",
            "headshot": "file/path"
        },
        "3": {
            "firstName": "FirstName",
            "lastName": "LastName",
            "headshot": "file/path"
        },
        "position": "POS"
    });
    // Remove object when the number decreases
    $scope.page.offense.topRow.pop();
}

The challenge I am facing is detecting when the user decreases the number in the input box. Additionally, I am unsure how to distinguish between value increase and reduction. Using ng-model for `page.offense.topRow.length` results in an array with missing indexes after the last one because it first increases the length before pushing the object, creating gaps like [1, 3]. Any suggestions or solutions would be greatly appreciated!

Answer №1

Consider having two functions, createObj() for object creation and destroyObj() to remove the object from the array.

Now, if you need to adjust the number of objects based on a variable input, I recommend exploring the $watch function in AngularJS. One approach could be to track two variables - oldVar and newVar, compare them, and execute the necessary function accordingly. For example, if the initial value was 10 and the user changes it to 7, you would call the destroy() function thrice.

You can find more information about the $watch function in Angular's documentation here.

Additionally, this helpful discussion on Stack Overflow provides a simple example of how to utilize the $watch function: link.

Answer №2

It is recommended to utilize the ng-change attribute rather than ng-click when dealing with a number field. By doing so, you can ensure that the event is triggered even when keyboard entries or copy/paste actions are performed.

Subsequently, within your change handler function, retrieve the current value and employ the splice() method on the array to either extend or reduce its size.

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

Caution when using a React form: Value of `true` has been detected for a non-boolean attribute `validate`

I am trying to address a warning message that I have received index.js:1 Warning: Received true for a non-boolean attribute validate. If you want to write it to the DOM, pass a string instead: validate="true" or validate={value.toString()}. I ...

Commitment without anticipation of a resolution or rejection

While testing one of my AngularJs Services, I decided to write some Unit tests. Below is a sample code snippet that I have come up with: it('', function(done) { aDocument.retrieveServiceFile(extractedFileFeature) .then(function() { ...

Calculating the quantity of elements within a jQuery array

A JQuery array is proving to be quite problematic. Here's what it looks like, [125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32] Unfortunately, there are duplicates present in this array. My goal is to obtain the count of each unique element ...

Organize group data by month in a visually appealing table using HTML/PHP with

I have successfully implemented a code that prints HTML table rows from a database table and sorts them by date. The challenge lies in the fact that the date is stored as VARCHAR (due to a pre-existing project with an active database used in a PHP web app ...

What are the steps to connect to, fetch, save, and remove files from a remote file server using Node.js?

Currently working on a project in node.js that requires saving an uploaded file from a client onto a remote file server for later retrieval. While I'm familiar with accessing and storing files on the local file system using 'fs', I am unsure ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

Storing multiple entries in a single MySQL cell along with JSON data

I have numerous folders named after different series on my website. Each series folder contains its own chapters, with each chapter containing images. As my website is a manga (comic) site, I want to store the paths of these folders and images in MySQL and ...

What are the best methods for looping through ids in MongoDB and executing actions on them?

I am working with an entity object that has the following response: [ { "public": false, "_id": "5eb6da3635b1e83", "createdAt": "2020-05-09T16:28:38.493Z", "updatedA ...

Which option is better: installing plotly.js or plotly.js-dist using npm?

When it comes to plotly.js and plotly.js-dist, what exactly sets these two packages apart from each other? Notably, the installation instructions for plotly.js on npmjs.org specify running 'npm install plotly.js-dist' - why is this necessary? W ...

Storing blank information into a Mongodb database with Node.js and HTML

Can someone please assist me with solving this problem? const express=require("express"); const app=express(); const bodyparser=require("body-parser"); const cors=require("cors"); const mongoose=require("mongoose"); ...

What is causing this code to malfunction?

Currently delving into the world of Ajax, I've been following a tutorial and have crafted the script below: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function MyFunction(){ var xmlhttp; if(windo ...

Issue with Angular: Unable to update model before modal closure on submit

I have a search form that is displayed within a modal window created using Angular UI Bootstrap. The input fields in the form update the ng-model when submitted. <script type="text/ng-template" id="mobileSearchPanel"> <form> ...

What is the best way to switch a boolean state in React using TypeScript?

Hey there! I'm diving into the world of React and TypeScript. My goal is to toggle a boolean state (true/false) using a handler function. While I've come across solutions in ES6, I'm struggling to grasp how it can be implemented in TypeScri ...

Using JavaScript regex to substitute white spaces and other characters

Here is a string I need to modify: "Gem. Buitentemperatuur (etmaal)" I want to remove all spaces, capital letters, and special characters from the string so that it becomes: "gem_buitentemperatuur_etmaal" ...

Exploring Angular unit testing using Jasmine: Techniques to customize or delete spyOn

Current software versions for AngularJS and Jasmine: AngularJS v1.2.26 Jasmine v2.2.0 I am facing an issue with a spyOn. When attempting to change or remove its behavior, I encounter the following error message: Error: getUpdate has already been spied u ...

The Gateway to Github: Unveiling the Mysteries through a

I need assistance in creating a static web page that can extract and showcase all the latest pull requests from a specified GitHub repository. My intention is to utilize octokit.js, but it seems to be designed for node.js. Is there any simple approach to ...

Gridsome's createPages and createManagedPages functions do not generate pages that are viewable by users

Within my gridsome.server.js, the code snippet I have is as follows: api.createManagedPages(async ({ createPage }) => { const { data } = await axios.get('https://members-api.parliament.uk/api/Location/Constituency/Search?skip=0&take ...

Tips for displaying the message "{"POWER":"ON"}" within the else if statement (this.responseText == ({"POWER":"ON"})) {

Hey everyone, I'm trying to adjust the color of a button on my webpage based on the response I receive from this.responseText. I understand the JSON response, but for some reason, I can't seem to incorporate it into my code. If anyone could lend ...

Executing multiple nested `getJSON` requests in a synchronous manner using jQuery

I am facing an issue with my code that connects to an API using $.getJSON. It retrieves JSON data and then iterates three times through a for loop because the data has 3 objects. During each of these iterations, it makes another $.getJSON call to fetch spe ...

Type of variable that is not an array

I need a quick way to check if a value is an object {} but not an array []. The code I currently have is: function isPlainObject(input) { return !Array.isArray(input) && typeof input === 'object'; } Is there a more concise method to a ...