ngModel is not taken into account when processing form data

Attempting to make use of a dynamic form in AngularJS, the code snippet below has been utilized:

<dynamic-form 
template="formTemplate"
        ng-model="formData"
        ng-submit="processForm()">
</dynamic-form>

The controller script includes the following lines:

$scope.formData = {}; // A JavaScript object is needed to store the form's models.

$scope.formTemplate = [];

The 'onsuccess' function looks like this: console.log('User registration form :'+ response); // The form-id will be transformed to a string // var form-id = response.form-id; var result = toArray(response); $scope.formTemplate = result;

}

function toArray(obj) {
  var result = [];
  var model = [];var type = [];var label = [];
  for (var prop in obj) {
    var value = obj[prop];
    angular.forEach(obj.fields, function(val,key){
        if(val.field_type != ''){type.push(val.field_type);}
        else{type.push(0);} 
        model.push(key);
    });
  }
  for(var j=0;j<model.length;j++){
    if(type[j] === 'textfield' || type[j] === 'password'){
        type[j] = 'text';
    }
    else if(type[j] === 'email'){
        type[j] = 'email';
    }
   else{
      type[j] = type[j];
   }

    console.log("result.. " + model[j] + "......"+ type[j]);
     result.push(
       {
           "type": type[j],
           "label": model[j],
           "model": model[j]
       }
     );
  }
  console.log("Result..." + result);
  return result;
}

This dynamic form library is being used: https://github.com/danhunsaker/angular-dynamic-forms

However, while the given example in the library works fine, the scenario above does not. Any ideas on what might be causing the issue? Is it related to model evaluation?

The sample response provided by me is as follows:

 var response =        {  
   "form-id":"user_register_form",
   "fields":{  
      "name":{  
         "field_type":"textfield",
         "description":""
      },
      
      "mail":{  
         "field_type":"textfield",
         "description":""
      },
      "field_first_name":{  
         "field_type":"textfield",
         "description":""
      },
     "field_gender":{  
         "field_type":"radio",
         "options":{  
            "male":"Male",
            "female":"Female"
         },
         "description":""
      }
     
   }
}

Answer №1

It seems like the issue lies in the fact that your result variable is holding a $resource object instead of a regular object. You can resolve this by making the following changes:

function successHandler(response) {
  var result = convertToArray(response);
  $scope.templateForm = angular.toJson(result);
}

Answer №2

For those who come across this now, the issue lies with the library being unable to handle form re-rendering when the template changes. It can be quite challenging to manage all the aspects involved in re-rendering a form, especially when it already contains data, and I haven't fully grasped all the requirements.

I would advise steering clear of the library I was using and opt for one of the alternatives listed in its README. These alternative libraries are generally more reliable and regularly updated.

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

Utilizing auto-generated Nonce for Content Security Policy in a Node.js/Express web application

I've exhausted all possible solutions in my attempt to create a nonce and pass it successfully to the CSP and inline scripts with the nonce variable. Despite reading numerous articles, the guidance on accomplishing this task remains vague. Fortunately ...

Troubleshooting issue with Django forms and JavaScript interactions

For the past day, I've been grappling with a particular issue and haven't made much progress. My setup involves using a django inline form-set, which displays all previously saved forms along with an additional empty form. To show or hide these f ...

Do not reveal result of coin flip using Javascript and API

Even though I meticulously copied my professor's parsing process, the display isn't turning out as expected. It seems like something is off in my code. <div class="main"> <p>Heads or tails? click to toss the coin</p> & ...

"Learn the trick to concealing a modal and unveiling a different one with the power of jquery

Whenever I try to open a modal, then click on a div within the modal in order to close it and open another one, I encounter an issue. The problem is that upon closing the first modal and attempting to display the second one, only the background of the seco ...

Looking for assistance with overriding kendo UI validation requirements

I'm looking to customize the date validation in my code to validate the date as DD/MM/YYYY. Here's my current code snippet and I'm getting an error message that says: Unable to get property 'methods' of undefined or null referen ...

I have incorporated jquery-1.2.6.js into my project but I am encountering difficulties utilizing the live method

C# foreach (DataRow Row in oDs.Tables[0].Rows) { LitPreferances.Text += "<Li ID=LI_" + Row["pk_Preference_Branch_ID"].ToString() +"_"+ Row["pk_Preference_BranchType_ID"].ToString() +">" + Row["Branch_Name"].ToString() + "&nbsp;&nbsp;< ...

Leveraging document.getElementById alongside css modules

When trying to retrieve an element that is using a css module, I encountered a problem where the id of the element changes after rendering. As a result, document.getElementById("modal") returns null. import React from "react"; export const HandleClick = ...

ngTable select all data that has been filtered

I have encountered an issue with selecting only the rows from an ng-table that have been filtered. The current code filters the table rows successfully, but it also selects rows that are not displayed: Controller: let sampleData = [{id: 1, name: 'Jo ...

Loading content from external sources on the dashboard

I'm trying to figure out how to load an external URL () within the content of a Dashboard. My current code looks like this: .state('app.urlloading', { url: '/url-loading', controller:function($window){ $window.locat ...

Trigger callback function when user selects a date on the calendar using Material UI X Date Picker

I am currently utilizing the DateTimePicker component in material ui, version 5. I am looking for a way to intercept the callback triggered when a user clicks on a day in the calendar selector: https://i.stack.imgur.com/0Tlogm.png Although the DateTimePi ...

What is causing the 'info' object to be undefined?

transporter.sendMail(mailOptions,(error,info)=>{ if(error) console.log(error) console.log('Message Sent: '+info.messageId) console.log('Preview URL: '+nodemailer.getTestMessageUrl(info)) res.redirect('contacts', ...

Can an Expression be incorporated into the ng-model Directive?

I am facing an issue with my loop: <div ng-repeat="measure in CompleteDataSetViewModel.TargetMeasures"> </div> Within this loop, I have an input field: <input ng-model="CompleteDataSetViewModel.AnnualRecord.Target[measure.Name]_Original" ...

Determining age in a Class upon instance creation

Is there a way to encapsulate the age calculation function within the Member Class without resorting to global space? I want to automatically calculate and set an age when creating an instance. Currently, I have a function that works, but I'm curious ...

What is the approach for for loops to handle non-iterable streams in JavaScript?

In the realm of node programming, we have the ability to generate a read stream for a file by utilizing createReadStream. Following this, we can leverage readline.createInterface to create a new stream that emits data line by line. const fileStream = fs.cr ...

"Executing ng-click directive on a second click changes the route in AngularJS

Why does my ng-click only redirect to a new location on the second click? It should redirect to $location.path('/login.signin');, but it only works if I click the button again. It's strange. Where could this issue be originating from? Belo ...

What is the best way to send parameters in AngularJS?

I am currently retrieving the geolocation of the user using this method, and it is functioning successfully as shown in the view with {{lat}} and {{lng}}: (function () { var showController = function($scope, $http, $routeParams) { ...

Navigate a JSON object using JavaScript

As I continue to juggle learning code with my job, I am diving into the world of creating charts using AMcharts. My goal is to generate multiple data sets based on orientation and potentially expand further in the future. In the JSON snippet below, you can ...

Error: Unable to access the 'create' property of an undefined object while utilizing sequelize to register a user and add an entry

Whenever I try to execute this controller, an issue arises indicating a problem with the recognition of the .create method from the model. What is the correct way to import Sequelize in order to utilize it effectively? const db = require("../Models/m_use ...

Update picture using Vanilla Javascript for mobile display

I am looking to change my logo color to white when viewed on mobile devices. Currently, I have the following code for changing the logo on scroll using vanilla JavaScript. The code toggles between a dark and light logo based on the scroll position. Howev ...

Issue with Webpack - npm run start and build operation not functioning?

Although I typically use create-react-app for my React projects, I decided to create one without it. However, I am encountering issues with the webpack configuration as I am not very familiar with it: This is how my package.json file looks like: { " ...