Using ng-model within ng-repeat for data binding in AngularJS

My challenge is to connect a model called 'User' to a series of input fields. Since I don't know the specific fields in advance, I need to write generic code that dynamically sets up the form based on the available fields.

<script>
    function MyController($scope){
        $scope.fields  = ['name','password','dob'];
        $scope.user1 = {name:"Shahal",password:"secret"}
    };
</script>
<div ng-app ng-controller="MyController">
    <ul>
        <li ng-repeat="field in fields">
            <label>{{field}}</label><input type="text" ng-model="user1.{{field}}">
        </li>
    </ul>
    <pre>{{fields}}</pre>
</div>

I'm attempting to iterate through the fields and display an input field for each one (from the scope). However, the binding is not functioning correctly as I'm trying to evaluate an expression inside ng-model.

The goal is to have three input fields (name, password, dob) with the user1 object connected to each respective field.

Check out the fiddle here

Any assistance would be appreciated!

Answer №1

Check out the solution below

<script>
    function MyController($scope){
        $scope.fields  = ['username','email','phone'];
        $scope.user1 = {username:"JohnDoe",email:"johndoe@example.com"}
    };
</script>
<div ng-app ng-controller="MyController">
    <ul>
        <li ng-repeat="field in fields">
            <label>{{field}}</label><input type="text" ng-model="user1[field]">
        </li>
    </ul>
    <pre>{{fields}}</pre>
</div>

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

Launching a web application directly from a USB drive

Exploring the world of Javascript frameworks and nodejs, I recently encountered a unique requirement that got me thinking about their practical application. The requirements are as follows: --I need to create a lightweight website that can be run from a U ...

Encountering an error while including ngmin in the r.js build file

Currently, I am attempting to utilize ngmin with requirejs's r.js as outlined in a guide found here. Unfortunately, I have encountered issues and cannot seem to make it work. Despite installing both ngmin and requirejs globally and locally using npm, ...

Configuring $scope.items for Angular Data Binding

I have a service that includes the following function, public object Get(AllUsers request) { var users = XYZ.GetAllUsers(); var userList = users.Cast<XYZ>(); return new AllUsers { UsersAcc = userList.Select(ConvertToEntity). ...

PlateJS: Transforming HTML into data

Trying to implement a functionality where clicking on a button retrieves an HTML string. The objective is to have this rich text editor within React-Hook-Form, and upon form submission, the value will be saved as HTML for database storage. Below is the pr ...

Newbie mishap: Utilizing an array retrieved from a function in javascript/jquery

After submitting the form, I call a function called getPosts and pass a variable str through it. My aim is to retrieve the data returned from the function. // Triggered upon form submission $('form#getSome').submit(function(){ var str = $("f ...

Is there a way to trigger this pop-up after reaching a certain percentage of the page while scrolling?

I've been working on a WordPress site that features an "article box" which suggests another article to users after they scroll to a certain point on the page. However, the issue is that this point is not relative but absolute. This means that the box ...

React Big Calendar encountered an error: The element type provided is not valid, as it is expected to be a string for built-in

Error One: The element type is invalid: it was expecting a string (for built-in components) or a class/function (for composite components), but received undefined. This could be due to not exporting your component correctly from the file where it's d ...

Discovering image file extensions in JavaScript using regular expressions

Can anyone provide me with a javascript regular expression to validate image file extensions? ...

How can I identify when a browser window is maximized using JavaScript or CSS?

I am currently working on a dashboard designed for static display on large monitors or TVs for clients. My main goal is to implement CSS styling, specifically a snap-scroll feature, but only when the display is in 'fullscreen' or 'maximized& ...

Modal windows allow for passing variables through the use of resolve binding

I am currently working with the following directive: angular.module('ui.bootstrap.demo').directive('warningDirective',function() { return { restrict: 'EA', scope: { showwarning: '=', warningmes ...

Incorporate JavaScript to dynamically fetch image filenames from a directory and store them in an array

By clicking a button, retrieve the names of images from a folder and store them in an array using jQuery. I currently have a script that adds images to the body. In the directory images2, there are 20 images stored. The folder images2 is located in my i ...

Generating unique identifiers and names for duplicated input fields in a form, which change dynamically

Innovative approach: When dealing with multiple replicated inputs, changing the id and name attributes can be a hassle. How can we ensure that each input remains unique, especially in a real project with several inputs like component_date and component_own ...

Having trouble getting the Keycloak provider to work with Next-Auth?

It's puzzling to me why my next-auth integration with Keycloak server is failing while the integration with Github is successful. import NextAuth from "next-auth" import KeycloakProvider from "next-auth/providers/keycloak"; import ...

Issues with updating data using PUT routes in Slim Framework v3

After upgrading to Slim v3, all my GET and POST routes are functioning correctly, but the PUT routes are encountering issues. I have a class where I have implemented this: $this->slimObj->put('/path/{ID}', array($this, 'method')) ...

AngularJS custom directive with isolated scope and controller binding

I am looking to create a directive that includes both scope parameters and ng-controller. Here is the desired structure for this directive: <csm-dir name="scopeParam" ng-controller="RegisteredController"> <!-- Content goes here--> {{na ...

npm is facing difficulties while trying to install the scrypt package. It is prompting the requirement

When attempting to run a blockchain application, I encountered an error message that reads: npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] install: node-gyp rebuild npm ERR! Exit status 1 npm E ...

Guide on how to load just the content section upon clicking the submit button

Here is an example of my code: <html> <head> <title>Test Loading</title> </head> <body> <div id="header"> This is header </div> <div id="navigation" ...

Integrating a feature for displaying No Results Found

I am struggling to modify a script for auto-completing search fields. My goal is to include a "No Results Found" option along with a hyperlink when no matching results are found. I'm having difficulty figuring out how to add an else statement to displ ...

What is the reason for React Native's absence of justify-self functionality?

I'm trying to figure out how to align an item on the right side of a row with other children aligned to the left. While I could use "position: absolute; right: 0" to achieve this, I'm curious if there's a more efficient way to do so. It seem ...

Modify a field within MongoDB and seamlessly update the user interface without requiring a page refresh

I am currently working on updating a single property. I have various properties such as product name, price, quantity, supplier, and description. When sending the updated quantities along with all properties to MongoDb, I am able to update both the databas ...