Populate the ng-model attribute dynamically based on the data in a JSON

Here is a JSON example that I have:

fields: [
        {
          name: "my_field_name",
          type: "text",
          placeholder: "place holder text"
        }],

I aim to dynamically generate form controls based on the field type and assign them an ng-model value equal to their name.

This is my approach for generating these fields:

<div ng-repeat="field in fields">
            <div ng-if="field.type=='text'" class="form-group">
                <label class="control-label">{{field.name}}</label>
                    <input type="{{ field.type }}"
                           ng-model="{{ field.name }}"
                                 class="form-control"
                                 required
                                 placeholder="{{ field.placeholder }}"
                    />
            </div> ....other types

In this scenario, the generated output should be like this:

<div ng-repeat="field in fields">
            <div ng-if="field.type=='text'" class="form-group">
                <label class="control-label">my_field_name</label>
                    <input type="text"
                           ng-model="my_field_name"
                                 class="form-control"
                                 required
                                 placeholder="{{ field.placeholder }}"
                    />
            </div>

However, the ng-model attribute does not recognize the {{}} syntax and results in an error.

Syntax Error: Token '{' invalid key at column 2 of the expression [{{ field.name }}] starting at [{ field.name }}]

Is there a way to resolve this issue?

EDIT:: I found a solution! By utilizing the $index variable provided by ng-repeat, I was able to create unique identifiers without any conflicts. Special thanks to: AngularJS - ng-repeat to assign/generate a new unique ID

Answer №1

Avoid the use of interpolation braces {{}} when using ng-model. Instead, it should reference a property variable.

ng-model="field.name"

Answer №2

Consider not using interpolation with ng-model

<input type="{{ field.type }}" ng-model="field.name" class="form-control" required placeholder="{{ field.placeholder }}"

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

Retrieving JSON information using jQuery

Is there a straightforward way to retrieve JSON data using jQuery? I have valid JSON that needs to be pulled efficiently. The JSON output looks like this: { "title": "blog entries", "items" : [ { "title": "Can Members of the D ...

developing a durable data hook with function support

As I work on developing a new hook to persist filter state, I encounter a challenge with some of the filters containing complex objects like dates which may include functions. The goal is to be able to store and retrieve these functions from local storage ...

Implementing React component that clears state upon selecting a place with Google Autocomplete

I've encountered a issue while using the Google Autocomplete component. Whenever I select a place and use the onPlaceSelected function to save it into a state array (input) of the parent component, the previous value gets replaced with an empty array ...

Codeigniter: How to use the .ajax() method to retrieve a value and display it in an input field?

Apologies for revisiting this question, but I am still struggling to solve this issue! About six months ago, I encountered a problem with receiving values from the server and displaying them in an input field. The specific question is: When I click the ...

What is the best way to retrieve the current CSS width of a Vue component within a flexbox layout grid after it has been modified?

There's something about this Vue lifecycle that has me scratching my head. Let me simplify it as best I can. I've got a custom button component whose size is controlled by a flex grid container setup like this: <template> < ...

Angular throws a 404 error when making a JSONP http request

I've been incorporating Mailchimp integration into an Angular application. For using it in pure JS, I retrieved the code from the embedded form on the Mailchimp site: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js ...

What is the best way to send AJAX post data to a Node.js server?

I am currently facing an issue with passing a unique ID object back to the server side using Ajax after making an API call. I need help figuring out what might be going wrong in my code. This is the client side code snippet where I loop through a JavaScri ...

Updating configuration file for Next.js

Typically, Next.js relies on the next.config.js file for configuration settings. Is it possible to modify this to use a different file name such as my.next.config.js? ...

What are the steps for implementing oncopy in Angular?

If I attempt the following: <div oncopy="myfunc('{{angularvar}}')">Copy me</div> Then an error message is displayed: Interpolations for HTML DOM event attributes are not permitted. It is recommended to use the ng- versions (such ...

The AJAX response is not functioning as expected

I've encountered an issue with my AJAX code for an online food store. Every time I run it, a pop-up message saying something went wrong appears instead of the expected output. I suspect there might be an error in either the connection handlers or the ...

Tips for integrating Google Analytics with React

In my react application, I have various pages: Main Service Contact Profile (private) etc.. To monitor user activity using Google Analytics, I came across the react-ga library which serves the purpose well. However, I find myself having to initialize G ...

Activate the ability to upload files if the check box is checked

How can I ensure that when the show checkbox is true (show = Boolean type), the file upload is enabled by default when the checkbox is not checked? I have tried the following code but it is not functioning properly; the enable/disable feature does not wo ...

Why does a Vue component throw errors prior to being rendered?

In the Home view, there are two components: Filter and Results. The Results component relies heavily on data from the vuex store, which is influenced by the Filter component. Once the filters are applied and the user interacts with Filter, the necessary da ...

Problem with hyperlinks: next character inadvertently added into the <a> tag in the TinyMCE user interface

I'm facing a challenge and struggling to come up with a solution. It could be due to incorrect setup or oversight on my part, but I suspect it might also be a bug. The issue is with the TinyMce setup applied in a Div (editable). setup: function (edi ...

Error: The formdata contains an unexpected field (Please upload an image)

I have been encountering the same error on the server side no matter what I do while trying to upload an image file. If anyone can point out what I might be missing, I would greatly appreciate it. javascript: const filePicker = document.getElement ...

Ways to retrieve inner document elements within the DOM console

After locating the selector with document.getElementsByClassName('top'), I am now attempting to access the contents of a deeply nested document within the HTML structure. https://i.sstatic.net/GCx8e.png It seems that this nested document is bei ...

Creating a dedicated login page separate from the single page application structure

My angularJS single page application functions as an admin dashboard, but I want to restrict access to only logged-in users. The issue I am encountering is that when I create a login template, it typically blends in with the admin dashboard due to the natu ...

When trying to convert to JSON in node, the process fails. However, the data can still be

I am currently working on converting an array to JSON in order to send it to a client. The data I see in the console is as follows: [ NL: [ true, true, true, true, true, true, true, true, true, true, true, true ], ...

How to dynamically reduce the number of columns in a textarea using jQuery according to its content

Does anyone know how to make a textarea shrinkwrap the text inside on blur? The default number of columns is 10 or 15 and I want the textarea to adjust its width based on the text content. I have tried the following code: $('textarea').on(&apos ...

Using Jquery to attach an event listener to an iframe

**I am currently utilizing a jQuery textselect plugin to trigger alerts based on the selected text anywhere on the page, and it is functioning well with code like this: $(document).ready(function() { $(document).bind('textselect', function( ...