Loading an Angular form dynamically upon button click

Looking to develop a dynamic page where various forms can be loaded upon button press. Each button triggers the addition of a new form with unique input fields corresponding to that button. The objective is to ensure that forms load in the sequence of button presses, with each form having distinct input fields based on the button clicked.

Check out my progress on Plunker:

http://plnkr.co/edit/OQYmoi99K1BZl4YwIMGG?p=preview

HTML

<ul>
            <div ng-repeat="form in forms">
              <div ng-if="showTransport(form)">
                <li class="list-group-item">
                  <div>{{from.name}} Name:
                    <input type="text" class="xdTextBox" ng-model="form.fields.tName" /> Comment:
                    <input type="text" class="xdTextBox" ng-model="form.fields.tComment" />
                  </div>
                </li>
              </div>

              <div ng-if="showLodging(form)">
                <li class="list-group-item">
                  <div>{{from.name}} Name:
                    <input type="text" class="xdTextBox" ng-model="form.fields.lName" /> Comment:
                    <input type="text" class="xdTextBox" ng-model="form.fields.lComment" />
                  </div>
                </li>
              </div>
            </div>
          </ul>

JavaScript

var app = angular.module('myApp', []);
var frmCnt = 0;

app.directive('ngIf', function() {
    return {
        link: function(scope, element, attrs) {
            if(scope.$eval(attrs.ngIf)) {
                // remove '<div ng-if...></div>'
                element.replaceWith(element.children())
            } else {
                element.replaceWith(' ')
            }
        }
    }
});

app.controller('MainCtrl', function($scope) {

  $scope.forms = [{
      name: "form_1",
      type: 't',
      fields: [{
        tName: '',
        tComment: ''
      }]
    }];

  $scope.addTransport = function() {
    frmCnt++;
    $scope.forms.push({
      name: "form_" + frmCnt,
      type: 't',
      fields: [{
        tName: '',
        tComment: ''
      }]
    });
  }

  $scope.addLodging = function() {
    frmCnt++;
    $scope.forms.push({
      name: "form_" + frmCnt,
      type: 'l',
      fields: [{
        lName: '',
        lComment: ''
      }]
    });
  }


  $scope.showTransport = function(form) {
      return form.hasOwnProperty("type=='t'")
  }
  $scope.showLodging= function(form) {
      return form.hasOwnProperty("type=='l'")
  }

});

I'm encountering difficulties in making it run smoothly. Any guidance or tips will be highly valued.

Answer №1

Upon initial inspection, it became evident that

return form.hasOwnProperty("type=='t'")
and
return form.hasOwnProperty("type=='l'")
consistently result in false outcomes. My suggestion would be to modify this logic as follows:

if(form.hasOwnProperty('type')){
  return type === 't' 
} 
return false;

I have made a copy of your plunk to test the changes: http://plnkr.co/edit/8K8JHVIbzQQgN6QnssJe?p=preview

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

Rendering elements dynamically using ng-repeat following an AJAX request

Feeling frustrated, I made an $http request ApiService.get_request_params("api/endpoint").then( function(data) { $scope.customers = data }, function(err) { } ); The $scope.customers should be bound to an ng-repeat. I can see the ...

Error occurs when using Vue 3 Transition component with a child <slot> tag

I have developed a unique component that enables me to incorporate a smooth fading transition without the need to repeatedly use the <transition> element: <transition mode="out-in" enter-active-class="transition- ...

Verifying the selection state of a dynamically generated checkbox with JavaScript

I have a table with checkboxes. Each time a button is clicked, I dynamically add new checkboxes to the table like so: var cell3 = row.insertCell(2); cell3.innerHTML = '<input type="checkBox" value=\"selected?\" style="cursor:poin ...

Emit Observables within deeply nested callback functions

Hey there! I'm currently working on a web app using Angular2/4 and I've encountered an issue with Observables. My goal is to call a function within a component and then have some code executed once that function completes. Here's the releva ...

An Array of objects is considered NULL if it does not contain any values before being iterated through

Working with Files in TypeScript (Angular 8) has led me to Encode the files in Base64 using the code below: private async convertToBase64(evidences: Array<EvidenceToDisplay>): Promise<Array<EvidenceToDownload>> { const results: Arr ...

Retrieving data from MySQL through AJAX does not yield any information

I have been following a tutorial from W3 schools on PHP and AJAX database. Majority of the content is working fine, however it seems that there is no data being retrieved from the MySQL database I created called "exercises" in the "exercisedb" database. B ...

Inconsistency in date serialization using JSON.stringify across various web browsers

I've written this snippet in an HTML file: alert(JSON.stringify(new Date())); To cater to older browsers lacking JSON.stringify(), I've included the latest json2.js (2009-09-29 version) along with jquery-1.3.2.js. In modern browsers with native ...

Angular $watch function not reflecting changes in the user interface

My $watch function is updating the model, but the bound controls in the UI are not reflecting the changes. Here is a screenshot of the updated model. https://i.stack.imgur.com/0ISg5.png The UI code looks like this: <form method="post" action="" role= ...

tips on retrieving the Vue element using a method in Vue.js

How can I dynamically add an element to the array by clicking a button in vue.js? Is it possible to call the method aggiungiViaggio on click, and how do I determine which viaggio I am currently in? Below is an example of the HTML: <div class=" ...

Challenges faced when retrieving data from a web API using JavaScript with REACT

Having trouble retrieving data from a Web API in React. The API URL is and I've stored it in a state called pokeData. When I do a console.log(pokeData), everything works fine. Likewise, there are no issues with console.log(pokeData.types). However, ...

Having trouble retrieving a specific object from an array using EJS

When re-rendering my form with any errors, I am able to display the errors in a list. However, I would like to access each error individually to display them under the invalid input instead of all at the bottom of the form. Here is what I have tried so f ...

Instructions on obtaining a distinct daily array from the weather API array that provides a detailed 5-day weather report every 3 hours

Seeking assistance with my weather app development on React using axios with the openweathermap.org API. Currently stuck on getting data formatted in a specific way from the 5-day forecast it provides, totaling 40 reports over the 5 days. The API response ...

What is the best way to change the name of a property within an object

I need to update the names of properties in a nested object. { 0: {value: "can_view"}, 1: {value: "can_create"} } The desired output should be: { user_can: "can_view", user_view: "can_create" } ...

"Downloading an image from an encoded base64 canvas triggers an error due to exceeding the maxUrlLength

I'm using javascript to create a canvas drawing on my webpage and then convert it into a base64 image format. After that, I encode the URL of the image to obtain an encoded URL. I came across a post where it was mentioned that using window.location.hr ...

How can the data from a factory be utilized within the same controller but in a separate file in an AngularJS application?

When trying to route from home.html to profile.html, there seems to be an issue with the execution of the profile.js script. I have data in script.js that is written in a factory. When the profile button is clicked, the page routes to profile.html, but the ...

Encountering TypeScript errors when utilizing it to type-check JavaScript code that includes React components

My JavaScript code uses TypeScript for type checking with docstring type annotations. Everything was working fine until I introduced React into the mix. When I write my components as classes, like this: export default class MyComponent extends React.Compo ...

When querying a document, the Mongoose array is missing

When querying for documents with an array, I'm encountering an issue where the returned documents do not include the array. Below is my code: Query Code (async () => { const data = await Lesson.find({signed: {$exists: true}}); cons ...

retrieving information from the database and passing it to the controller

I'm in the process of developing a new API with Express, following the MVC architecture. However, I've been facing difficulties getting the data to successfully return from the database access file to the controllers file. Initially, I attempted ...

The simplest method to make HTML elements inaccessible to the Simple HTML Dom Parser in PHP

Imagine a scenario where a basic web application is running and utilizing Simple HTML Dom Parser. The code snippet below demonstrates this: <?php include('simple_html_dom.php'); $html = file_get_html('http://someurl.com'); ...

Can Date.parse be utilized within an Angular expression?

I am struggling with the code below: function Ctrl($scope) { $scope.dt = new Date('2012-07-16T00:00:00'); var format = { day: '2-digit', month: '2-digit', year: 'numeric' }; $s ...