AngularJS tutorial: Display multiple inputs using ng-repeat based on a specified number

I am new to AngularJS and I have a question about how to utilize the ng-repeat feature.

Most examples I find demonstrate reading from a service and then using ng-repeat to loop over that data.

In my scenario, an admin can create an invitation for guests and set a property called:

total_in_party = 4;

Based on the value of "total_in_party", I want to display 3 input fields for each guest in the party.

For example:

<div ng-repeat="guest in party">
  <input type="text" ng-model="guest.first_name" />
  <input type="text" ng-model="guest.last_name" />
  <select ng-model="selectedGuestMeal" ng-options="meal.id as meal.name for meal in meals"></select>
</div>

In this instance, it should generate those 3 input fields 4 times.

I believe I am close, but I am unsure how to create the party object if there is no existing data stored in it?

If I am approaching this problem incorrectly, please do not hesitate to provide guidance!

Answer №1

I recently encountered this very issue and found a solution by creating an array of guest objects within the scope and binding it to a form using ng-repeat.

To see a working example of my solution, you can visit: http://plnkr.co/edit/2aYSLYe0IcRGXR7Lm0HR?p=preview

app.controller('MainCtrl', function($scope) {
  $scope.numberOfGuests = 1;
  $scope.guests = [];

  addGuests($scope.numberOfGuests);

  // Watch for changes in the number of guests and update the array accordingly
  $scope.$watch('numberOfGuests', function (newValue, oldValue) {
    if (!newValue) {
      return;
    }

    newValue = parseInt(newValue, 10);
    oldValue = parseInt(oldValue, 10);

    if (!isNaN(oldValue) && newValue > oldValue) {
      var numberOfGuests = newValue - oldValue;
      addGuests(numberOfGuests);
    } else {
      $scope.guests.length = newValue;
    }
  });

  function addGuests(numberToAdd) {
    if (!isNaN(numberToAdd) && numberToAdd > 0) {
      for (var i = 0; i < numberToAdd; i++) {
        $scope.guests.push({});
      }
    }
  }
});

Here is how the view looks:

<body ng-controller="MainCtrl">
  <form>
    <p>Number of Guests <input type="number" ng-model="numberOfGuests" ></p>
    <table>
      <tr ng-repeat="guest in guests track by $index">
        <td>{{$index + 1}}</td>
        <td><input type="text" ng-model="guest.name"></td>
        <td><input type="text" ng-model="guest.email"></td>
      </tr>
    </table>
  </form>
  <pre>{{guests | json}}</pre>
</body>

Answer №2

To create a list of guests in your Angular controller, you can define a guests property within the $scope object based on the value of total_in_party:

function initializeGuestList(totalInParty) {
  $scope.guests = [];
  for (var i = 0; i < totalInParty; i++) {
    $scope.guests[i] = {
      first_name: '',
      last_name: '',
      meal: ''
    };
  }
}

In your HTML template using ng-repeat, utilize $index to iterate through the guest list:

<div ng-repeat="guest in guests">
  <input type="text" ng-model="guests[$index].first_name" />
  <input type="text" ng-model="guests[$index].last_name" />
  <select ng-model="guests[$index].meal" ng-options="meal.id as meal.name for meal in meals"></select>
</div>

This code snippet has not been fully tested yet, but it is expected to function correctly :)

Answer №3

Monitor the total_in_party value and adjust the number of guests accordingly

JavaScript Code Snippet

$scope.$watch('total_in_party', function(newValue, oldValue) {
  if (newValue != null) {
    console.log(newValue, oldValue);
    if (newValue > oldValue) { //add
      var difference = newValue - oldValue;
      for (var i = 0; i < difference; i++) {
        $scope.party.push({
          first_name: "",
          last_name: "",
          selectedGuestMeal: null
        });
      }
    } else if (newValue < oldValue) { //subtract
      var difference = oldValue - newValue;
      $scope.party.splice(0, difference);
    }
  }
});

Check out this plunkr demo for reference

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

Guide to setting up Mongodb with mongoose in the latest Next.js 13.3 update

I'm having trouble connecting MongoDB with Mongoose in Next.js 13.3 Version. I keep getting errors when trying to import the connectDb file or UserSchema file in api/getProducts/route.js file. Can someone please help me with step-by-step instructions ...

Synchronously executing Twitter posts

Hello there! I've been using this code found here to embed Twitter posts on my website. It's been working perfectly on certain pages, like in the forums, but I've run into an issue while browsing through user profiles. The post history for e ...

Obtain attributes from an array of objects organized by the individual objects

Hello there! I am currently working with an array called artists[] which consists of Proxy objects. Each Proxy object is also an array of objects, with each inner object containing a property called "artistName". Interestingly, the third Proxy ha ...

Utilizing AngularJS to dynamically bind one view to various data models at different intervals

After creating a view with divs and input boxes in an HTML file, I now want to reuse it in multiple places but with different data models bound to it. "I mean change in ng-model of input tags" The traditional approach would be to create the same view repe ...

Refresh your AngularJS Bindonce directives with the power of the refreshOn attribute

After making some edits to my bindonce table, I am attempting to force refresh it. However, I am struggling to understand how to utilize the bindonce refreshOn attribute. Here is my HTML Code: <tbody bindonce="filteredItems" refresh-on="refreshTaskLis ...

A self-destructing javascript/jquery function that removes itself after running

For a very detailed analytics insight, I am sending an ajax request to my controller in order to update the user's interaction (such as which pages they visit or like) and store this information in my MongoDB. All I want is for this script to be dele ...

Data not being properly transmitted in React Express GET request

Hey everyone! I have successfully set up an endpoint on a local server for my React application. I created a GET endpoint to send data to the requester, but I am facing an issue where no data is being sent to any client requesting from this particular en ...

Updating multiple subdocuments with Mongoose

My goal is to update a specific subdocument called addresses (which is working fine) and then update all other subdocuments except the one that was just changed. Whenever an address is changed to have is_preferred set to true, I need to update the previous ...

Troubleshooting: Firefox not executing AJAX call in onchange function

I have developed a form with a select_tag that includes an onchange function: Form (advertisments/_form.html.erb): <div class="controls advertise-medium-select"> <%= select_tag 'advertisment[medium_id]', options_for_select(@mediums ...

How to link a JavaScript file within a PHP document

I have an HTML file (index.html) that is using JavaScript to call a PHP file (pdj.php) and display the output in a div (pdj), which is functioning correctly. $.ajax({ url: '../command/pdj.php', type: "POST", data: ({xparam: xpara ...

Using Javascript to automatically replace content when the page is loaded

Having trouble with my fullCalendar jquery calendar and the 'eventClick' method. When I click on an event, the URL is getting encoded incorrectly. For example, I'm trying to pass a Wordpress URL like this: http://sitedomain.com/?post_type= ...

Troubleshooting CORS Problem in VUE JS 3 while Making API Request from Localhost to External API服务

I've been dealing with a CORS issue for quite some time now. I've tried all the solutions on Stack Overflow, but nothing seems to be working for me. Can anyone help me figure out what's wrong with my code? I'm using VUE JS 3 and trying ...

Issues arise when attempting to use the Android KeyUp, KeyDown, and KeyPress events in conjunction with Angular2

I am encountering an issue where I consistently receive a keyCode of 229 in Android Chrome browsers when running either: <input type="text" (keydown)="testKeyCodes($event)"/> <!-- or --> <input type="text" (keyup)="testKeyCodes($event)"/& ...

The unpredictability and variability of AngularJS templateURL values

I'm currently working on a "name" directive that can accommodate both first and last names. Here is the code I have so far: index.html <div data-dm-name label="First Name:" info="first_name"></div> <div data-dm-name label="Last Name: ...

Filtering data in AngularJS ui-grid 3.x using an input box

I've implemented the ui-grid and integrated an input box. My goal is to connect this input box to filter the grid column, without relying on the default textbox provided by the ui-grid. Seeking assistance on how to achieve this. Any suggestions? ...

Ensuring Uniform Card Sizes in Bootstrap 4 for Multiple or Single Cards

Having trouble creating a page with N cards (single or multiple): https://i.sstatic.net/20WXc.png A single card appears like this: https://i.sstatic.net/01bP0.png I am unsure why the single card is not rendering correctly compared to multiple cards. T ...

Mongoose Troubles in NodeJS

I am reaching out to seek assistance with a problem I am facing that I have been unable to resolve on my own. My tech stack includes nodejs, express, and mongodb (particularly using mongoose). Although my express server is running smoothly, I am encounter ...

Issue with processing secure 3D payments on live mode in Stripe

I am currently implementing 3D secure payment on a website. It works perfectly in the test environment with test cards, but when I switch to live keys, it does not generate a pop-up for user confirmation. Instead, it completes the payment without any confi ...

Creating an Angular reactive form with checkboxes and initializing a formArray with an existing array

I have a dynamic array of LkBoardTypeList fetched from a server. My goal is to push that array to form an array upon initialization, essentially displaying checkboxes based on the Board's name or ID in the array. I know how to push an empty array in r ...

Exploring the Power of Elasticsearch with Datatables

I'm attempting to utilize functions from an Elasticsearch instance in conjunction with datatables to exhibit results. Currently, I am only able to display 10 results, regardless of the query used. Even though there are 141,000 results in Elasticsearc ...