Using Angular's ng-repeat to display a combination of different elements

I'm currently working on transitioning a form from .Net MVC to Angular. I've successfully used ng-repeat to generate the input fields within the form, which is working well. However, I now need to incorporate select fields along with the text input fields.

How can I mix text fields and select fields within a single form using ng-repeat? Is this even achievable? I am fairly new to Angular. Please note that the code provided below is just a quick example and will be refactored for proper structure:

<div ng-app>
   <div ng-init="profiles = [
       {id: 'first-name', label: 'First Name', type: 'text'},
       {id: 'middle-name', label: 'Middle Name', type: 'text'},
       {id: 'last-name', label: 'Last Address', type: 'text'},
       {id: 'suffix', label: 'Suffix', type: 'text'},
       {id: 'social-security-number', label: 'Social Security Number', type: 'text'},
       {id: 'DateOfBirth1', label: 'Date of Birth', class: 'datePicker hasDatepicker valid', type: 'text'},
       {id: 'years-in-school', label: 'Years in School', type: 'text'},
       {id: 'marital-status', label: 'Marital Status', type: 'select'}
     ]">
    <h2>Borrowers Information</h2>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
    <div ng-repeat="profile in profiles" class="control-group col-md-3">
      <label class="control-label" for="{{profile.id}}">{{profile.label}}</label>
      <div class="controls">
        <input data-val="true" data-val-required="Please enter a valid first name." id="{{profile.id}}" name="{{profile.id}}" value="" type="{{profile.type}}" class="{{profile.class}}">
      </div>
    </div>
   </div>
 </div>
<script>

Answer №1

To efficiently handle different types of inputs in Angular, you can utilize either ng-switch or ng-if directives and include select options as an array within your form object like shown below:

https://jsfiddle.net/82u6gj26/

Angular

vm.person = {};
vm.form = [{
    type:'text',
    label:'First Name',
    id:'first_name'
},
{
    type:'select',
    label:'Marital Status',
    id:'marital_status',
    options:[
        {id:'Single',name:'Single'},
        {id:'Married',name:'Married'}
    ]}
];

HTML

<div ng-repeat="form in ctrl.form">
    <div class="form-group">
        <label>{{form.label}}</label>
        <div ng-switch="form.type">
            <input
                type="text"
                ng-switch-when="text"
                ng-model="ctrl.person[form.id]">

            <select
                ng-switch-when="select"
                ng-model="ctrl.person[form.id]"
                ng-options="s.id as s.name for s in form.options">
                <option>Select One</option>
            </select>
        </div>
    </div>
</div>

Answer №2

If you want to conditionally display elements in AngularJS, you can utilize the ng-if directive (https://docs.angularjs.org/api/ng/directive/ngIf).

Here's an example of how you can use it:

...
<div class="controls">
 <input ng-if="profile.type != 'select'">
 <select ng-if="profile.type == 'select'">
 </select>
</div>
...

Answer №3

Achieving this is definitely possible!

    <div ng-repeat="profile in profiles" class="control-group col-md-3">
          <label class="control-label" for="{{profile.id}}">{{profile.label}}</label>
          <div class="controls">
            <input data-val="true" data-val-required="Please enter a valid first name." id="{{profile.id}}" name="{{profile.id}}" value="" type="{{profile.type}}" class="{{profile.class}}" ng-if="{{profile.type!='select'}}">
            <select id="{{profile.id}}" name="{{profile.id}}" class="{{profile.class}}" ng-if="{{profile.type=='select'}}">
             <option value="{{option.value}}" ng-repeat="option in profile.options">{{option.caption}}</option>
</select>
          </div>
        </div>
       </div>

Utilize ng-if or ng-show to determine which element should be displayed.

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

Discovering the offset location using touchmove

Struggling with a code for dragging/moving an element via touchscreen. The code is functional, but encounters a common issue - unable to drag from the touchpoint itself. Every movement initiates from the edge of the element, no matter where the touch begin ...

eliminating list item from unordered list depending on the input of either first or last name

My objective is to refine a lengthy list as the user types in a search for a specific person by first or last name. The current code I have functions adequately, but encounters an issue when there is a space in the input field. My goal is to allow users to ...

Error in AngularJS $http due to incorrect HTTP status code on failure

While attempting to construct a JSONP request using AngularJS's $http Service, I am encountering issues where the wrong HTTP status code 404 is returned instead of 500, and the page's body is missing as well. Here is the situation: The URL I am ...

Unable to install @uirouter/angularjs using npm

Encountering an error while trying to npm install @uirouter/angularjs, the error message displayed is: npm ERR! code E404 npm ERR! 404 Not Found: @uirouter/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f7f8f1e3faf7e4bfb9f8d ...

Animating Divs with jQuery to Expand their Size

I am currently designing a services page for my portfolio website. The layout consists of three columns, with the central column containing a large box and the left and right columns each containing three smaller boxes. These smaller boxes function as clic ...

loading the css and javascript files based on the specified prop parameter

In the process of working on a ReactJS file that utilizes the react-ace library, I currently have the following code implemented. import React, { Component } from 'react'; import 'brace/mode/html'; import 'brace/theme/monokai&apos ...

What is the method for retrieving the name of the currently selected HTML element?

After using jQuery to select certain tags, I am now trying to obtain the name of each tag: $('select, :checkbox, :radio').each(function(){ // ... }); To accomplish this, I have attempted the following code: $('select, :checkbox, :radio ...

Discovered an issue with Sentry debugging where a lengthy string is being returned as undefined

We are currently in the process of developing an Angular 1.x application that utilizes Bootstrap components. Recently, we integrated Sentry debugging into our site and encountered the following error: 'PAPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDIN ...

Implement jQuery to toggle a class on click for added functionality

I am attempting to create a box that changes color when clicked. When the box is first clicked, it will turn red by adding the class red, and if clicked again, it will change to blue. The colors alternate with each click, but I am unsure of how to achieve ...

React.js issue: "Unable to iterate over 'this.state.product.response' as it is not a function"

I am a complete beginner diving into the world of React.js while working on constructing a CRUD application using Visual Studio 2017 with an MVC framework and Entity framework. I seem to have hit a roadblock and have been stuck for quite some time attempti ...

Convert a prop into a data attribute using Vue.js 2

I have a basic component being displayed as <House :_people="[{'name': 'Kevin'}, {'name':'Bert'}, {'name': 'Timmy'}]"></House> The structure of the component is like this: <templ ...

jQuery fails to function properly when using the .live("keyup") event

Below is the code snippet: $(document).ready(function() { $("#querybox").live("keyup", function(e) { var code = (e.keyCode ? e.keyCode : e.which); if (code == 13) { $("#querybox").blur(); } else { search(document.getElementB ...

Is foreach not iterating through the elements properly?

In my code, I have a loop on rxDetails that is supposed to add a new field payAmount if any rxNumber matches with the data. However, when I run the forEach loop as shown below, it always misses the rxNumber 15131503 in the return. I'm not sure what I ...

The functionality of res.send is not working correctly

Attempting to send a response from my express application to the front-end in order to display an alert. Here is what I have attempted in my app: if (info.messageId) { res.redirect('back'); res.send({ success: true }); } ...

ng-repeat isn't displaying the data

I have always been comfortable using the ng-repeat in Angular, but this time I seem to be facing a problem. I am trying to populate my DOM with data from a JSON file, but for some reason, the fields are not displaying as expected. Is there something wrong ...

Is there a way to schedule a function to run every 6 hours in node.js based on actual time instead of the device's time?

var currentTime = new Date().getHours(); if(currentTime == 6){ //function Do stuff } if(currentTime == 12){ //function Do stuff } if(currentTime == 18){ //function Do stuff } if(currentTime == 24){ //function ...

Bootstrap form toggle switch component for ReactJS

I'm having trouble figuring out why the default value for my react-bootstrap switch won't set to false (off). It seems like the only way it changes is when I trigger the onChange event handler. Am I overlooking something? Below is the section of ...

Use Angular UI Directive Typeahead to direct to a specific link

Currently, I am utilizing the Angular UI Bootstrap typeahead directive for a specific project in which I aim to redirect to a dynamic URL depending on the user's selection in the typeahead. Essentially, I want to utilize the typeahead as a search bar. ...

Simulating NextJS router triggers using Jest

I've been attempting to simulate NextJS router events using Jest. I came across a useful resource at NextJS router & Jest. The approach outlined there closely resembles mine. Unfortunately, the solution provided in that post is not yielding the d ...

Node.js local storage/cookie functionality

Running three different apps on Node.js at ports 3000, 3005, and 3007. I need to set a LocalStorage or Cookie variable at port 3000 and access it from the apps running at ports 3005 and 3007. Folder structure: nodep/ |-app.js (runs at port 30 ...