Utilizing AngularJS with multiple dynamically generated forms on a webpage: Extracting data from each form

I am facing a challenge with a web page I have created that uses PHP to generate forms for updating information via a REST API on a remote server.

The structure of the forms is as follows:

Textfield: name
textfield: description
select: type (ng-model="selection")
  option a
  option b
  option c
textfields f1, f2, f3: some may be hidden based on selection.
button triggers AngularJS function update() when clicked.

There are several of these forms scattered throughout the page. How can I retrieve the data entered into these fields to pass it to the update() function using AngularJS? My initial thought was to use JavaScript getElementById method, but I believe there must be a more elegant solution available.

Answer №1

When working with AngularJS, you have the ability to connect data to your form using the ng-model attribute.

Take a look at this example snippet from the documentation:

<form novalidate class="simple-form">
    Name: <input type="text" ng-model="user.name" /><br />
    E-mail: <input type="email" ng-model="user.email" /><br />
    Gender: <input type="radio" ng-model="user.gender" value="male" />male
    <input type="radio" ng-model="user.gender" value="female" />female<br />
    <input type="button" ng-click="reset()" value="Reset" />
    <input type="submit" ng-click="update(user)" value="Save" />
  </form>

http://plnkr.co/edit/qr1HdCqgr7jvf5aR0Gb2?p=preview

It is recommended to have models structured within one object, where each field represents a property of that object (for instance, user.email in the above example).

Subsequently, within your controller, you can easily access the form values by referencing the corresponding scope variable (e.g., $scope.user).

Answer №2

To assign data to each field in a form, you can utilize the ng-model directive. When updating, you can retrieve this data from the $scope object.

For example:

<input type="text" ng-model="form1.name">
<input type="text" ng-model="form1.description">
...
...

<input type="text" ng-model="form2.name">
<input type="text" ng-model="form2.description">

JavaScript:

Within the update method, you can access the data using $scope.form1.name, $scope.form1.description.

Answer №3

If you want to create tabs for each form, where clicking on a tab opens the corresponding element for editing without knowing the total number of elements in advance, you can use this approach.

<div ng-app>
    <article ng-controller="AplicationCtrl">
        <ul>
            <li ng-repeat="item in items">
                <a href="javascript:;" ng-click="changeSelected($index)">Tabs {{$index}}</a>
            </li>
        </ul>
        <br/>
       <div>
           <input ng-model="selectedItem.name"/>
           <input ng-model="selectedItem.description"/>
        </div>

        <a href="javascript:;" ng-click="update()">Update values</a>
    </article>
</div>

function AplicationCtrl($scope) {
    $scope.items = [
        {
            name: 'this is name1',
            description: 'desc 1'
        },
        {
            name: 'this is name 2',
            description: 'desc 2'
        },
        {
            name: 'this is name 3',
            description: 'desc 4'
        }
    ]

    $scope.changeSelected = function (index) {
        $scope.selectedItem = $scope.items[index];
    }

    $scope.changeSelected(0);

    $scope.update = function () {
        console.log($scope.items);
    }
}

You can view an example here: http://jsfiddle.net/9c567te7/

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

Transclusion with multiple slots in AngularJS

Attempting to incorporate a component in AngularJS 1.5.8 with multi-slot transclusion. The test performs well when utilizing a directive, however, with a component, it appears that the slot cannot be located!. This is how the component is declared app. ...

JavaScrip $("").text(); is a straightforward way to recognize and extract

At the moment, I am utilizing the jQuery script below: $("TD.info > font").text(); when this specific HTML structure is present on a webpage: <td class="info"> <font> 3001474535 </font> </td> I had the idea to tweak t ...

Best practices for referencing attributes created with the data method in a Vue component

In my application, there is a section that displays a list of users along with a search box to filter names. The user information is fetched from a database and stored in app.users. I have created a component named 'user' to show the details of e ...

My changes to the HTML file are not being reflected in the browser, even after clearing the cache. This is happening in an Angular and Node.js application

I'm currently developing an application using Angular and Node.js. I've noticed that when I make changes to the HTML file, the browser isn't updating even after clearing the cache. Could this be a coding issue? Any suggestions on how to fix ...

How to iteratively process JSON array using JavaScript?

I am currently attempting to iterate through the JSON array provided below: { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "<a href="/cdn-cgi/l/email-pro ...

Is server-side rendering necessary for `browserHistory` in React Router?

I am a beginner in the world of React and currently diving into the complexities of routing. While hashHistory (/#/paths/like/this) proves to be functional, browserHistory (/paths/like/this) appears much cleaner. However, I noticed that when reopening URLs ...

Parcel-Bundler is unable to resolve critical security issues

I recently followed a tutorial by Kevin Powell on SASS and Parcel through YouTube. I was able to successfully set up the SASS part and get the Parcel bundler working smoothly on one project, so everything seemed to be going well at that point. However, to ...

What is the best way to save the toggleClass value of various selectors along with their corresponding classes in localStorage?

I've been attempting to preserve the toggled class of multiple elements using local storage or cookies in order to maintain the toggled class after a page refresh. Despite trying various solutions such as js cookie and other tutorials, I've had n ...

Using jQuery and JSON data to dynamically populate a second dropdown menu with filtered options

I am working on a form with two drop-down menus and a text box. The first drop-down contains static values, while the second drop-down is populated dynamically from a JSON array. My goal is to filter the options in the second drop-down based on the selecti ...

Interactive Timekeeping Tool with AngularJS Alarm Feature

I have successfully implemented the functionality to display the system time and date. Additionally, I have set up textboxes for users to input the time they want to set as their first alarm. My current goal is to trigger a particular action once the syst ...

I'm facing an issue in React where using onChange is causing all DOM elements to be cleared. The input form functions correctly when used with a button, but for some reason, the onChange event does not

Currently, I'm working on a grid that can be resized using two input fields in the application. The setup involves an input for cells across, an input for cells down, and a button to set the grid, which is functioning well. However, I would like to ma ...

accessing the php script within a node environment

Hey there! I'm currently working on creating a chat system using socket.io, express.io, and node.js. So far, everything has been going smoothly as I've been following the documentation provided by these tools. However, when I attempt to integrat ...

"Alert: Jest has detected that an update to MyComponent in a test was not properly enclosed in an act() function, even though there was no actual update being made. Please

Here's a super straightforward test I've put together: it('renders', () => { const { toJSON } = render( <MockedProvider> <MyComponent /> </MockedProvider> ) expect(toJSON()).toMatc ...

Protractor is able to achieve successful test results without actually executing the tests

SYMPTOMS When running Protractor, the tests pass successfully, but the pages do not load. Instead, they appear blank with "data:text/html" in the address bar (refer to the screenshot). Although the tests show as passed, there are 0 assertions being made. ...

Refreshing a page in MVC after making an Ajax call to the controller

In my controller, I have the following code: public async Task < ViewResult > Favourites(string ids) { // API call to fetch book data if (data != null) { var bookList = JsonConvert.DeserializeObject < Book[] > (data); ...

Guide to verify the user selection within a select form

Here is a form with a select field: <form method="post" name="posting_txt" onSubmit="return blank_post_check();" id="post_txt"> <select style="background: transparent; border-bottom:5px;" name="subname" class="required"> ...

Transforming the shopping cart with redux-saga

Hey there! I've been working on implementing a shopping cart feature using redux-saga. The current code seems to be functioning properly, but I have some concerns about the way I'm handling the cart state. It looks like I might be mutating the ca ...

How do I combine Firefox binary specification with adding the Firebug extension when using Selenium?

Presently I am utilizing the code below. var co = require('co'); var WebDriver = require('selenium-webdriver'); var SeleniumServer = require('selenium-webdriver/remote').SeleniumServer; co(function *() { // async var ser ...

What causes a user to log out when the page is refreshed in a React/Redux application?

Each time the page is reloaded in my React/Redux application, the user gets logged out, even though I have stored the token in localStorage. There seems to be an error somewhere. The token should ideally be saved when the user logs in and not lost upon rel ...

Which is better: express.Router() or app.get() for serving routes

I am currently working with Express 4 server for Node.js Express comes with a built-in router, which is utilized as follows: in app.js var router = express.Router(); app.use(router); app.use('/users', usersRoutes); in userRo ...