Establish Angular data for all fields in the form

Being a beginner in Angular, I'm struggling with creating a form to update user information. Here's a snippet of my controller:

        // Fetch organization data from the database            
        dataService.allOrganization().then(function (data) {
            vm.allOrg = data;
        });
        // Fetch user data from the database
        dataService.getOneUser(theId).then(function(data) {
            vm.oneUserUpdate = data;

        });

        $scope.user = {};
        $scope.submitForm = function(theId) {
            $scope.user.idUser = theId;
            dataService.updateUserPost($scope.user).then(function (data) {
                vm.oneUserInfo = data;//response from http request
            })
        }

And here's the corresponding view snippet:

<form name="userForm" ng-submit="submitForm(userDataCtr.oneUserUpdate.identities[0].user_id)">
            <div class="form-group">
                <label>Encryption Key :</label>
                <input type="text" class="form-control" name="encryption" ng-model="user.encryption" >
            </div>
            <div class="form-group">
                <label>Admin :</label>
                <select class="form-control" name="admin" ng-model="user.admin">
                    <option>Select...</option>
                    <option value="true">True</option>
                    <option value="false">False</option>
                </select>
            </div>
            <div class="form-group">
                <label>Organization ID:</label>
                <select class="form-control" name="organization" ng-model="user.organization">
                    <option>Select...</option>
                    <option ng-repeat="org in userDataCtr.allOrg" value="{{org.id_org}}">
                        {{org.name_org}}
                    </option>
                </select>
            </div>
            <div class="form-group">
                <label></label>
                <div class="checkbox">
                    <label><input type="checkbox" value="1" name="role_cro" ng-model="user.role_cro">ROLE_CRO</label>
                </div>
                <div class="checkbox">
                    <label><input type="checkbox" value="1" name="role_client" ng-model="user.role_client">ROLE_CLIENT</label>
                </div>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>

I'm looking for a way to automatically populate the form with the user's existing data, including pre-filled input fields, checked checkboxes, and selected organization options.

Any help would be greatly appreciated. Thank you.

Answer №1

Ensure to keep your models up to date. For example:

dataService.getOneUser(theId).then(function(data) {
        vm.user={};
        vm.user.encryption = data.encryption;
        vm.user.role_client = data.role;
    });

When displaying on the view:

<div ng-controller="Mycontroller as my">
<div class="form-group">
                <label>Encryption Key :</label>
                <input type="text" class="form-control" name="encryption" ng-model="my.user.encryption" >
</div>
</div>

Remember to use the controller instance in your view to make it work smoothly.

Answer №2

When integrating data from a controller or directive into a template, it's crucial to bind it to the controller's $scope.

.controller('myFormController', function () {

    dataService.allOrganization().then(function (data) {
        // Update the $scope with the necessary data
        $scope.allOrg = data;
    });
});

These variables can now be linked to form fields using ng-model.

<input type="text" name="firstName" ng-model="allOrg.firstName">

Keep in mind that not all form elements work the same way. For more detailed examples of form binding, refer to the Angular form documentation.

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

Deleting an element from an array in JavaScript by its index

I'm currently working on a todo type app and I need to figure out how to remove an array element. Adding elements using element.push() is straightforward, but removing them is a bit more challenging. The remove button is nested within a template liter ...

Implementing a Jquery check based on a checkbox

Hey, I'm having an issue with a condition. When I uncheck the checkbox, it doesn't uncheck. I've tried to make a block display, but the JavaScript isn't working. I attempted to add: document.getElementById("Reload").style.display = "b ...

Steps for changing a component's properties when the component serves as a property

The scenario I'm facing involves a component that receives a prop named button. This button prop is essentially a Component itself, containing various other props within it. My goal is to override the specific prop called type within this nested struc ...

Consolidate test outcomes from various nodes in the stack into a single graph

Nowadays, web applications consist of a variety of different technology stacks. Developers utilize languages like Ruby, Python, PHP, JavaScript, and C for the backend, as well as frameworks such as AngularJS and EmberJS for MVC/client-side code. To ensure ...

Remain on the current webpage following the submission of comparable ajax-forms

Seeking assistance with an issue involving Ajax that I believe is unique. Desired Outcome I have a newsfeed with various posts and interspersed forms, such as polls, for user interaction and submission of results. Objectives Users should be able to inter ...

Node.js & Express: Bizarre file routes

It's quite strange how my local paths are functioning. Let me show you an example of my directory structure: public > css > bootstrap.css public > js > bootstrap.js templates > layout > page.ejs (default template for any page) tem ...

What is the best approach to comply with the EsLint rule "react-hooks/exhaustive-deps" and properly implement componentDidMount using hooks in React with a warning level?

After reviewing the React documentation, it appears that componentDidMount is now implemented using hooks as shown below: useEffect(() => { // your code here }, []) For example, if you wish to make an API call within this hook: useEffect(() => { ...

Automatically assigning a default dynamic value to a dropdown option using Vue.js

I need to set a default selected value for the select option element, but I am facing difficulty in achieving the desired result. <template> <select v-model="tutor_work.start_year"> <option>{{tutor_work.start_year}}< ...

Restrict the PHP generated Json response to display only the top 5 results

I need to modify my search bar so that it only displays the top 5 related products after a search. public function getProducts() { if (request()->ajax()) { $search_term = request()->input('term', ''); $locatio ...

Sending Dual Parameters to PHP File Using AJAX

Currently, I am facing an issue where I can successfully pass one value to a Bootstrap modal via AJAX, but my code stops working when I try to pass a second value. JavaScript function claimOrder(str, stre){ if (str=="") { document.getElementById("txtH"). ...

Edit CSS attributes within Angular 2+ framework

When using jQuery, we have the ability to do the following: JQuery('.someStyle') .css({"background", "red"}) This allows us to directly change the CSS property in style. While working with Angular 2+, we can use [style.<property>] for ...

The eel feature results in no output

During my Python program development using the Eel module, I encountered an issue. The problem is that the eel.getImgSrc(path) function returns null when trying to retrieve image's byte data. Take a look at this example: -----web/main.js------ async ...

Tips for consolidating outputs from three different APIs using JavaScript and AJAX? [Pseudo code example]

For my school project, I am working on an e-commerce aggregator site where I need to combine product data from 3 different APIs (like Aliexpress and Amazon) into one homepage. Although I can retrieve results from each API individually, I'm facing chal ...

Is JSONP necessary for accessing the API subdomain?

Currently in the process of setting up an application with the API being hosted at http://api.project.com while the main app will reside at https://app.project.com. This app is going to be entirely based on angular.js. I'm curious if JSONP is the onl ...

How can an HTML5 application be configured to enable access to intranet and local files?

It's a known fact that accessing the local path of a file added using a file input field or drag-and-drop is not possible even with the new FileAPI. Whether this limitation is good, bad, or ugly is not up for debate. The FileAPI specs clearly state th ...

Ways to conceal <td>s in angularjs on specific rows during ng-repeat

In the first <tr>, I have a table with many <td> elements that I am populating using ng-repeat. <tr ng-repeat="receipt in $data"> <td data-title="voucher number"> <span>{{receipt.voucher_no}}</span> </td ...

Tips for loading a partial view page in a specific element using Angular JS after clicking a button

I'm facing an issue with my AngularJS partial view page not loading after a button click. I've set up the initial rendering page, but when we click the button, the partial view page doesn't render properly because the angular modules are not ...

Seamless social login integration for registering with Stormpath

Transitioning from C# and PHP to Node.js has presented some challenges, especially when working with the Stormpath API. I am currently trying to integrate social login on the registration page, but the pre-built option only allows it on the Login page. Al ...

Retrieve the element (node) responsible for initiating the event

Is there a way to identify which element triggered the event currently being handled? In the following code snippet, event.target is only returning the innermost child node of #xScrollPane, with both event.currentTarget and event.fromElement being null. A ...

ERROR: The data has reached its end prematurely (data length = 0, requested index = 4). Could this be a corrupted zip file?

Currently, I am developing a WhatsApp bot and storing the chat data in an Excel file using exceljs for further processing. In order to handle responses efficiently, I am utilizing promises to resolve them. Below is the function I have created to read the c ...