Creating a dynamic textarea input based on the number entered using AngularJS

Can a loop be simplified in AngularJs to easily determine the number of textarea inputs a user can fill?

<input type="number" class="form-control" min="1" max="4" value="1">


<div ng-repeat="...">
   <div class="form-group">
        <textarea class="form-control" rows="3"></textarea>
   </div>
</div>

</div>

Is there a straightforward way to iterate through a set number of times, like a for loop in AngularJs ng-repeat or an alternative method?

Answer №1

const app = angular.module("demo", [])
  .controller("DemoCtrl", function($scope) {

    $scope.itemCount = 1;

    $scope.items = [];

    $scope.onItemCountChanged = function() {

      // Check and update items as needed
      if ($scope.itemCount < $scope.items.length) {
        $scope.items = $scope.items.slice(0, $scope.itemCount - $scope.items.length);
        return;
      };

      // Add items if needed
      if ($scope.itemCount > $scope.items.length) {
        var numToAdd = Math.abs($scope.items.length - $scope.itemCount);
        for(var i = 0; i < numToAdd; i++) {
          $scope.items.push({ text: "item text" });
        }
      }
    };
  });

Here is the corresponding view:

<div ng-app="demo" ng-controller="DemoCtrl">
  <input type="number" min="1" max="4" ng-model="itemCount" ng-change="onItemCountChanged()" />

  <div ng-repeat="item in items track by $index">
    <textarea ng-model="item.text"></textarea>
  </div>

</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

Create shorter nicknames for lengthy reference names within the ng-repeat loop

Is it possible to assign an alias to a long reference name in ng-repeat? Currently, I have 2 complex objects where one acts as a grouped index for the other. Although the ng-repeat template code is functioning correctly, it's getting hard to read and ...

Exploring the power of regular expressions in Javascript

In my code, I am using the following regular expression: var re = new RegExp("(^|\\s)" + classname + "(\\s|$)"); I know that \s represents a white-space character and the caret symbol denotes the "beginning with". However, I am c ...

Tips for resolving issues with dynamically displaying state information based on a selected country

I'm currently working on a project that requires me to dynamically fetch the states of a specific country when a user selects the country of birth for their family members. To do this, I am utilizing AJAX. Due to limitations, I can only include detai ...

Using Backbone.js to dynamically filter a collection when a user clicks a specific element

update added more details about my progress so far. I'm currently in the process of developing an app that showcases the gists of members belonging to a specific organization, drawing inspiration from bl.ocks.org. My goal is to enable users to click ...

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 ...

necessity for a condition in Material UI input field

I need assistance with a function that I use to incorporate Material UI text fields into my code. The issue I'm currently facing is figuring out how to dynamically add the "required" attribute based on a boolean parameter that determines whether the f ...

Converting JSON into Typescript class within an Angular application

As I work on my app using angular and typescript, everything is coming together smoothly except for one persistent issue. I have entity/model classes that I want to pass around in the app, with data sourced from JSON through $resource calls. Here's ...

Streamlining all icons to a single downward rotation

I am currently managing a large table of "auditpoints", some of which are designated as "automated". When an auditpoint is automated, it is marked with a gear icon in the row. However, each row also receives two other icons: a pencil and a toggle button. W ...

The Firebase signInWithPopup functionality suddenly shuts down in a Next.js project

Incorporating the signInWithPopup function for signing in has been successful during the development stage on my local server. const firebaseAuth = getAuth(app); const provider = new GoogleAuthProvider(); const [{ user, cartShow, cartItems }, dispatc ...

Guide to Chrome's Document Object Model and JavaScript Reference

Does Chrome have a Javascript/DOM Reference page similar to the Mozilla Developer Network? I am curious about other websites that provide detailed information on Chrome's specific interpretations of web standards. ...

adjusting three sections within a flexible navigation bar

Having difficulties creating a dynamic navbar that changes on scroll and keeping the elements within the nav fixed when the menu options appear. For reference, you can check out this codepen: http://codepen.io/timothyfernandez/pen/azXQPV Any assistance w ...

Guide for incorporating Google maps into a Vue.js application

Can anyone help me with displaying a Google map using Vue.js? I've tried but it's not showing up, and there are no errors in the console. Below is the code I'm using, and I need to display the map within that specific div tag. <template& ...

Retrieve all unclean input fields based on table rows in AngularJS

I have an AngularJS form embedded within an HTML table that looks like this: <div ng-app="myApp"> <div ng-controller="MyCtrl"> <form name="inputData" id="inputData" ng-submit="submit()"> <table class="table"> &l ...

When the page loads, the HTML side menu will automatically scroll to the active item in a vertical

My website features a vertical side menu with approximately 20 items. The issue I am facing is that when a user clicks on an item, the destination loads but the side menu must be manually scrolled to find the active item if it's located at the bottom ...

"Why is it that when using jQuery, the .fail method doesn't accept arguments to deliberately

I am attempting to utilize custom JSON encoded data after intentionally triggering an error on the server (throwing an error on purpose) during a jQuery AJAX request. I am confused as to what is going wrong, as the header is correct and the data is being ...

Restricting the number of mat-chips in Angular and preventing the input from being disabled

Here is my recreation of a small portion of my project on StackBlitz. I am encountering 4 issues in this snippet: I aim to restrict the user to only one mat-chip. I attempted using [disabled]="selectedOption >=1", but I do not want to disable ...

ng-disabled is failing to interact with the $scope variable

Attempting something like this: <button class="btn btn-lg btn-block btn-section" ng-disabled="{{ selectedfruits.length }} < 5" > Show selected fruits</button> When inspecting in Chrome developer tools, the code appears as follows: &l ...

Implement input validation in React by enhancing the functionality of HTML input tags

Below is the input provided: const REGEX_EMAIL_VALIDATION = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}&bsol ...

Challenges concerning the communication between child directives in AngularJS

Issue Summarized: How can I access the controller of a child directive within a parent directive in AngularJS? Detailed Explanation: I am creating directives to manage input from a remote controller, similar to a TV controller, as HTML lacks efficient f ...

`How can you generate navigation paths using the ngRoute module?`

I am currently working on creating a basic navigation system like the one illustrated below: html: <html ng-app="myapp"> <body> <ul> <li><a href="pages/sub1">sub1</a></li> <li><a href="pages/ ...