Implement ng-model on an input field that is pre-filled with a value from a different model within the Angular

One challenge I am facing involves pre-populating an input field with user information, such as their email address or first name, if that data is available.

Initially, I set the value of the input field using $scope.userData. However, when I add an ng-model attribute to the input field, the value on the front-end appears blank.

For example:

Works as expected (input field displays user's email):

<input class="text-input" type="email" value="{{data.email}}">

Does not work (input field remains blank):

<input class="text-input" type="email" ng-model="formData.email" value="{{data.email}}">

I understand why this doesn't work—the formData.email is empty and the model overwrites the value. However, I need to save this information in formData to later submit a POST request to my service upon form submission.

As a newcomer to Angular, I want to avoid relying on jQuery and solve this issue through Angular itself.

So, how can I set the email field to a model for form submission while also populating the initial email data, if available?

Answer №1

To properly execute the desired action when the form is loaded, you can use the following code:

formData.email = data.email

In Angular, you can achieve this by utilizing the ngInit method. Assuming you have a function named initializeEmail that handles setting the email value, you can incorporate it like so within your form element (or any relevant location that has access to formData):

<form ng-init="initializeEmail(data.email)">

When Angular initializes, it will recognize this function and appropriately populate the email field in the formData object.

Answer №2

AngularJS utilizes bidirectional binding.

This means that when you input something with ng-model="formData.email", the scope value will change accordingly and can be accessed in the controller as $scope.formData.email. Conversely, if you modify the value of $scope.formData.email in the controller, it will automatically update the value of the corresponding <input /> in the view.

To establish a default address, simply remove the value attribute from the input and set the initial value of $scope.formData.email in the controller at the outset.

I highly recommend reviewing the official basic tutorial. It provides comprehensive explanations for everything related to AngularJS.

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

Clone all documents from a NodeJS mongoose collection and transfer them to a different server's database

I need assistance with migrating my database to a new server. My collection consists of approximately 410,000 documents, and I am looking to transfer them in batches of 100 to my new server that runs on mongodb. Below is the code I have written for this ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Loop Through Mongoose to Retrieve Multiple Objects

I am currently facing an issue while trying to retrieve multiple objects from MongoDB using mongoose. In my database, I have two primary collections known as user and order. The user collection consists of an array called 'order history', which ...

Minimize the number of HTTP requests by including CSS and JS files in PHP

I've been considering a method to reduce the number of HTTP requests made when loading a page by minimizing the amount of downloaded files, while still keeping separate files on the server. The thought process is as follows: <!DOCTYPE html> &l ...

Tips for utilizing Vue.js techniques to assign values to data properties

As a newcomer to Vue.js, I am in the process of learning how to display data retrieved from a server. In my new Vue app, I have defined a method: methods: { getData: function() { // making a request, parsing the response and pushing it to the array. ...

Which method proves to be quicker: storing data on a DOM element with a class attribute, or using jQuery data?

In my application, I have a render loop that constantly updates the appearance of several DOM elements based on data fetched from an external source. Each element needs to have presentational classes applied according to this data. For example: var anima ...

Having difficulty accessing information from JSON files with Angular JS

There appears to be empty data being added to the table. https://i.sstatic.net/cimze.jpg I'm encountering difficulty retrieving data from a Json file using Angular Js. I've been attempting to fetch the Json data from a URL by clicking a functio ...

Creating a Custom Form Control in Angular 2 and Implementing Disable Feature

I have developed a unique custom control using ControlValueAccessor that combines an input[type=text] with a datepicker. While the template-driven forms accept it without any issues, the situation changes when implementing the model-driven approach (react ...

Is it possible to synchronize functions in node.js with postgresql?

I’m facing some challenges in managing asynchronous functions. Here is the code snippet that's causing the issue: var query = client.query("select * from usuario"); query.on('row', function(user) { var queryInterest = client. ...

Utilizing Angular Directives and Controllers for Improved Efficiency

I have developed a custom dropdown option selector which is functioning well. It includes functions to fetch data from a specified URL in order to populate a list. However, the issue arises when I attempt to reuse this component in a different section of ...

Tips for wrapping a function call that may occasionally involve asynchronous behavior to ensure it runs synchronously

I am dealing with a function that functions as follows: _setDataChunk: function (action) { var self = this; /* some code */ var data = self._getDataChunk(action); populateWidget(data); } Sometimes GetDataChunk cont ...

Material UI filterSelectedOptions not functioning properly on initial search with multiple autocomplete

When I utilize the filterSelectedOptions prop in my autocomplete feature, it functions as intended when using a pre-defined chip. Check out image1 for an example: image1 However, when a brand new typed option is entered, it ends up duplicating multiple ti ...

Transforming RGB Decimal Color to HEX RGB Color in Three.js

Currently, I am facing a challenge in my task involving colors while working with three.js, a JavaScript library. In this particular task, I need to convert decimal color codes (e.g. 12615680) into formats like #FF0000 or 0xFF0000. I am seeking a JavaScr ...

Guide to executing the refresh() function on a kendo-grid using an Angular controller

Currently, I'm experimenting with implementing various recommendations to refresh a kendo-grid, such as the one found on this page. The crux of the matter is that in the HTML code, I have: <div kendo-grid="vm.webapiGrid" options="vm.mainGridOptio ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

Guide to adding a JS file from npm package to a new page in Nuxt.js

I am facing an issue where I have multiple npm packages containing client-side scripts that I need to include in different pages of my Nuxt.js project. I attempted to achieve this by using the following method: <script> export default { head: { ...

Refreshing the Canvas post-submission

I have created a form that allows users to add notes and sign on a Canvas. However, I am facing an issue with clearing the canvas after submission, as it does not seem to work properly. The rest of the form functions correctly. The goal is to clear both t ...

What are the ways to activate an element in vue js?

Is there a way to modify the code so that the function triggers with just one click instead of two? export default { methods: { remove(){ $('.remove-me button').click( function() { removeItem(this); }); ...

When using mapStateToProps in React Redux, it may encounter difficulties in reading nested values

I feel like I must be overlooking something very obvious, possibly related to Immutable.js/React/Redux. Here is a method I have... function mapStateToProps(state){ console.log(JSON.stringify(state.test)); //prints all nested properties and object ...

The x-axis title in Apexcharts is consistently misaligned

Dealing with some issues regarding the placement of the x-axis title in my column chart. The position of the title seems to vary based on the y-values range, as illustrated in these examples: Example 1 Example 2 Below is the code I am using: Code block ...