Tips for creating AngularJS forms which display radio buttons and populate data from a JSON file

I'm having trouble displaying the json data correctly.

  • How can I show the radio buttons from my json file (plunker demo)?

  • Additionally, I want to validate the form when it is submitted.

Here is the HTML code:

<my-form ng-app="CreateApp" ng-controller="mainController">

    <form ng-submit="submitForm()" novalidate>

        <fieldset>
            <div ng-repeat="field in result.fields">
              <label for="{{field.type}}">{{field.label}}</label>
              <input 
                    ng-required="{{field.required}}"
                    value="{{options.value}}"
                    type="{{field.type}}" >

              <form-error ng-show="{{field.errorMessages.required}}"></form-error>
              <form-error ng-show="{{field.errorMessages.invalid}}"></form-error>
            </div>


        </fieldset>

        <button type="button" ng-click="onValidate(); return false;"> Validate</button>
        <button type="submit" ng-disabled="userForm.$invalid"> Submit </button>
    </form>


</my-form>

Answer №1

Start by initializing a value on the controller

        $scope.topTeam = {};

        $http.get('data.json').success(function(response) {
        $scope.result = response;
        var fields = response.fields;
        $scope.topTeam.val = fields.answer.options[0].value;
        console.log($scope.topTeam);
        console.log($scope.fields);
      });

HTML:

<form ng-submit="submitForm()" novalidate>
          <fieldset>
            <div ng-repeat="field in result.fields">
              <label for="{{field.type}}">{{field.label}}</label>
              <input ng-if="field.type != 'radio'" ng-required="{{field.required}}" value="{{options.value}}" type="{{field.type}}">
              <div ng-if="field.type == 'radio'">
                <div ng-repeat="option in field.options">
                  <input type="{{field.type}}" ng-model="topTeam.val" value="{{option.value}}">{{option.label}}</br>
                </div>

              </div>



              <form-error ng-show="{{field.errorMessages.required}}"></form-error>
              <form-error ng-show="{{field.errorMessages.invalid}}"></form-error>
            </div>
          </fieldset>

          <button type="button" ng-click="onValidate(); return false;"> Validate</button>
          <button type="submit" ng-disabled="userForm.$invalid"> Submit </button>
        </form>

Answer №2

If you're looking to iterate through radio options, one suggestion is to consider using an Angular form library like angular-formly, as mentioned by @charlietfl.

<fieldset>
  <div ng-repeat="field in result.fields">
    <div ng-if="field.type === 'radio'">
      <span>{{field.label}}</span>
        <div ng-repeat="option in field.options">
          <label for="{{option.label}}">{{option.label}}</label>
          <input ng-required="{{field.required}}"
                 value="{{options.value}}"
                 id="{{options.label}}"
                 type="{{field.type}}" >
        </div>
    </div>
    <div ng-if="field.type !== 'radio'">
      <label for="{{field.type}}">{{field.label}}</label>
      <input ng-required="{{field.required}}"
             value="{{options.value}}"
             type="{{field.type}}" >
    </div>
    <form-error ng-show="{{field.errorMessages.required}}"></form-error>
    <form-error ng-show="{{field.errorMessages.invalid}}"></form-error>
  </div>
</fieldset>

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

The program is designed to only allow up to two images to be wrapped

I'm struggling with a short jQuery program that I need help with. The problem is, I can't seem to get it to wrap more than two images in the same row. My goal is to create a website that side-scrolls, and I thought this approach would be the simp ...

Tips for updating ng-repeat when the modal is closed?

Scenario: I've got a page (angular) containing a repeater. <tr ng-repeat="row in results.leads"> <td>{{row.SubmittedByName}}</td> Inside the repeater, there's a button in a column that triggers a modal to modify the data o ...

Updating during an ongoing state transition is not possible, especially within the `render` method. The `render` method should strictly be a pure function based on the props and state provided

Currently, I am utilizing react and react hooks for the front-end development of my project. Unfortunately, I have encountered an error message that states: index.js:1 Warning: Cannot update during an existing state transition (such as within `render` ...

Verify whether the input field contains a value in order to change certain classes

My meteor-app includes an input field that dynamically changes position based on whether it contains content or not. When a user begins typing, with at least one character, the input field moves to the top of the page. In my current approach, I am using a ...

the term 'this' does not pertain to the user object within the mongoose model

Here is a snippet of my code that saves a user object to a database using Express: api.post('/signup', function (req, res) { var user = new User(); user.name = req.body.name; user.email = req.body.email; user.setPassword(req.body ...

Adding JQuery elements to the map pane

I recently decided to upgrade one of my projects to use the Google Maps API v3 instead of v2. In v2, I used the following code to append a div to the map pane: $("#marker_popup").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE)); Is there a straightforward ...

Enhancing the efficiency of JavaScript code

Imagine you have a web application processing 1,000,000 user logins per hour. and the code below is executed during each user login: if (DevMode) { // make an Ajax call } else if (RealMode) { // make another Ajax call } else { // Do something ...

Facing an issue with AngularJS where I am able to retrieve data.data, but struggling to assign it to a scope variable

Currently, I am developing a website using AngularJS that retrieves questions and multiple-choice answers from an Amazon Web Services table. This data is used to dynamically create a prelab questions page. The http get request is functioning properly; when ...

What are the steps to transform my database object into the Material UI Table structure?

I have a MongoDB data array of objects stored in products. The material design format for creating data rows is as follows: const rows = [ createData('Rice', 305, 3.7, 67, 4.3), createData('Beans', 452, 25.0, 51, 4.9), createData ...

Showing information from asynchronous AsyncStorage.getItems in React Native

In my app, users have to validate their success on challenges by clicking a validation button which saves the "key":"value" pair of the challenge using this function: async function validate(challenge_nb) { try { await AsyncStorage.setItem(challenge_n ...

The role of the colon in extracting data from an AJAX request

Curiosity arises around the usage of the colon, :, in data. It is clear that the data is sent to list.php, but the exact process remains unclear. function paint(val){ $(".loading").css("display","block"); $.ajax({ type:"POST", ...

Alternate Row Colors Using Odd/Even CSS Styling for Main Headings

In my expand/collapse table, I have set up alternating row colors (dark grey and light grey) that adjust automatically when expanding or collapsing. The challenge I'm facing is that for certain rows, I want to apply a specific background color using ...

Add styling to a window popup and close it when focus is lost in Ext JS

I am trying to implement a specific functionality where the popup arrow should be at the edge of the textbox as shown in the image below. How can I achieve this? Additionally, how can I make sure that clicking outside the control destroys the popup instead ...

Resolve the issue with automatically generating SCSS type definitions (style.d.ts) for Preact within a TypeScript webpack setup

Utilizing webpack with Preact 10.x (nearly identical to React) and TypeScript in the VSCode environment. Following an update from Node version 12 to version 14, there seems to be a problem where *.scss files no longer automatically generate their correspo ...

Having trouble with the "setValue" property being undefined error. Looking for a solution to input text into a codeMirror element using Selenium WebDriver with Java

Currently, I am attempting to input text into a textarea field that is recognized as CodeMirror. Below is the code snippet I have been working with: {... WebElement scriptField = this.getDriver().findElement(By.cssSelector(".CodeMirror-line>span")); ...

Securing access across multiple routes in a React application

I am facing a challenge in my React app where I need to verify the logged-in state before allowing access to multiple routes. Despite consulting various resources like Stack Overflow for solutions such as creating a Private Route, I have only found example ...

The search text box is mysteriously absent from each column in the datatables

I am utilizing jQuery Datatables to construct a table with data retrieved from MySQL. This is how my table appears: LOT_LOCATION, Zone Attribute, LOTID, Design_ID, Board_ID1, QA_WORK_REQUEST_NO, QA_CONTACT_NAME, QA_PROCESS_NAME, CURRENT_QTY, Date, Temp ...

React router will only replace the last route when using history.push

I'm working on implementing a redirect in React Router that triggers after a specific amount of time has elapsed. Here's the code I've written so far: submitActivity(){ axios.post('/tiles', { activityDate:thi ...

Causes of the error message 'TypeError: res.render is not a function'

I have set up an express application with the following code: var express = require('express'); var router = express.Router(); var passport = require('passport'); var User = require('../models/user'); var request = require(&a ...

What is the process for completing a form with Protractor and TextAngular?

I'm currently attempting to submit a form that utilizes TextAngular for certain input fields. Despite my efforts, I haven't been successful in finding information on how to fill out these fields. The closest solution I found was this, but when I ...