Boosting data transfer with AngularJS

I am currently working on an AngularJS application where I use $scope.forms to generate various input fields in the HTML section through ng-repeat.

One thing that is puzzling me is how to populate the values: [] with data from the

attributes: ["title", "firstname", "lastname", "address"]
inputs.

Could someone please help me understand how to transfer the input values into the values key? Or is there a more efficient solution you could suggest?

function sampleCtrl($scope) {

  $scope.forms = [
    {
      title: "Something",
      attributes: ["title", "firstname", "lastname", "address"],
      values: [] //I need the values from the attributes here
    },
    {
      title: "Something else",
      attributes: ["title", "name", "job", "address"],
      values: [] //I need the values from the attributes here
    }   ]; }

http://jsfiddle.net/U3pVM/18198/

Answer №1

Check out @Grundy's response for a straightforward solution without modifying your model.

May I offer an alternative approach that considers using ng-model to connect the input value? The idea is to represent the attribute-value pair as a tangible entity. For instance:

$scope.forms = [
    {
        title: "Something",
        pairs: [{label: "title", value: ""}, {label: "firstname", value: ""}]
    }
];

This format of the view model facilitates easier binding in the interface:

<div ng-repeat="pair in form.pairs">
    <input type="text" placeholder="{{pair.label}}" ng-model="pair.value" />
</div>

I propose this method because the $scope integrates smoothly with views when structured appropriately. If an alternative structure (such as an array of values) is required for backend purposes, you can convert the view model back accordingly. For example:

var values = $scope.forms[0].pairs.map(function(p) {
    return p.value;
});

Take a look at this modified fiddle for a comprehensive demonstration.

Answer №2

You might want to take a look at ng-model. In the model, you can use values[$index] so that the values in the values array correspond to the order of the values in the attributes array.

function sampleCtrl($scope) {

  $scope.forms = [
    {
      title: "Something",
      attributes: ["title", "firstname", "lastname", "address"],
      values: [] //I would like to have the values from the attributes here
    },
    {
      title: "Something else",
      attributes: ["title", "name", "job", "address"],
      values: [] //I would like to have the values from the attributes here
    }
  ];

}
body {
    font-family: courier new;
}

h1 {
    font-size: 24px;
    margin: 0 0 20px;
}

h2 {
    font-size: 18px;
}

.form {
    margin: 0 0 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
    <h1>Form</h1>
    <div ng-controller="sampleCtrl">
      
        <div class="form" ng-repeat="form in forms">
          <h2>{{form.title}}</h2>     
          <div ng-repeat="input in form.attributes">
              <input type="text" ng-model="form.values[$index]" placeholder="{{input}}" />
          </div>
            {{form.attributes}}
            {{form.values}}
        </div>
      
    </div>
  </div>

Answer №3

Here are the updates I made to your code snippet:

<div ng-app>
    <h1>My Form</h1>
    <div ng-controller="exampleCtrl">

        <div class="form-section" ng-repeat="section in sections">
          <h2>{{section.title}}</h2>     
          <div ng-repeat="field in section.fields" ng-init="modified = []">
              <input type="text" placeholder="{{field}}" ng-init="modified[$index] = section.values[$index]" ng-model="modified[$index]"/>
          </div>
       </div>     
   </div>
</div>

http://jsfiddle.net/ABC123/45678/

Answer №4

Here is a simple solution: Check out this updated fiddle

All you need to do is add an ng-model, which will point to the same index in both the attributes and values arrays.

<div ng-app>
    <h1>Form</h1>
    <div ng-controller="sampleCtrl">

        <div class="form" ng-repeat="form in forms">
          <h2>{{form.title}}</h2>     
          <div ng-repeat="input in form.attributes">
              <input type="text" ng-model="form.values[$index]" placeholder="{{input}}" />
          </div>
        </div>
        <button ng-click="haha()">Test!</button>
    </div>
  </div>

No changes in JS are needed, just added a new function called haha() for testing purposes

function sampleCtrl($scope) {

  $scope.forms = [
    {
      title: "Something",
      attributes: ["title", "firstname", "lastname", "address"],
      values: [] //here I want the values from the attributes
    },
    {
      title: "Something else",
      attributes: ["title", "name", "job", "address"],
      values: [] //here I want the values from the attributes
    }
  ];

    $scope.haha = function(){
        console.log($scope.forms);
    }

}

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

Issue with Panel Settings and Tooltip in Amcharts

Looking for solutions to two specific issues that I am struggling with: I have two charts with multiple panels, each having only one scroll bar. My problem lies with the balloon text - when hovering over a balloon, I need to display two different texts ...

Leveraging the power of Bootstrap and JavaScript to implement a custom Toast feature

I am utilizing Bootstrap 4 to design Toasts, and I am presently developing a JavaScript function to generate a toast. My attempt to create elements within the JS file did not properly style it. index.html <!doctype html> <html lang="en"> ...

Blazor, the Razor Library, npm, and webpack are essential tools for front

Let me try to explain this clearly. I have a Blazor WebAssembly (WASM) project that is referencing a Razor library without any issues. The Razor library successfully compiles a JavaScript bundle using webpack. One of the components I am attempting to creat ...

Conceal the ::before pseudo-element when the active item is hovered over

Here is the code snippet I am working with: <nav> <ul> <li><a href="javascript:void(0)" class="menuitem active">see all projects</a></li> <li><a href="javascript:void(0)" class="menuitem"> ...

Is there a way to cancel a fetch request and initiate a new one right away?

Below is an illustration taken from MDN. The example showcases two buttons - one for sending a request and the other for canceling it. var controller = new AbortController(); var signal = controller.signal; var downloadBtn = document.querySelector(&apos ...

Achieving the highest ranking for Kendo chart series item labels

Currently, I am working with a Kendo column chart that has multiple series per category. My goal is to position Kendo chart series item labels on top regardless of their value. By default, these labels are placed at the end of each chart item, appearing o ...

What measures can be taken to block access to `angular.element().injector()` from the browser console in a secure production mode

In the production version of my code, I included the following lines: $compileProvider.debugInfoEnabled(false) angular.reloadWithDebugInfo = angular.noop After implementing the above code, I noticed that when I run this script in the browser console: an ...

Is there a way to work around the CORS policy in order to fetch data from URLs?

I have been developing a tool that can analyze URLs from an uploaded CSV file, search the text content of each URL, and calculate the total word count as well as the occurrences of "saas" or "software". The goal is to generate a new CSV file with the origi ...

Using a for loop to call a Node.js request function

I have arrays consisting of 8 elements each var array_pullrequest_id=["335","328","326","323","322","314","295","291"]; var array_uniqueName=["<a href="/cdn-cgi/l/email ...

Delete outdated information using Google Apps Scripts when the date is less than the current date plus a specified number of days

I have a Google Sheet where I need to filter out entries based on the number of days since the last check. Specifically, I want to keep only those entries where the number of days since the last check is greater than 10. You can find the Sheet here. fu ...

Instead of scrolling through the entire window, focus on scrolling within a specific HTML element

I currently have the following elements: #elementA { position: absolute; width: 200%; height: 100%; background: linear-gradient(to right, rgba(100,0,0,0.3), rgba(0,0,250,0.3)); z-index: 250; } #containerofA { position: fixed; ...

Showing a JavaScript variable on an HTML page

I have a challenge where I am attempting to showcase a variable using the code provided below: HTML: <div id="MyEdit">Money</div> JS: var price1 = 0; var current_value=document.getElementById("MyEdit").innerHTML; if (current_value == "msc" ...

Retrieve the data based on the page ID or slug using the Wordpress Rest API

Utilizing the power of the WordPress Rest API as the backend for my project and Nuxt.js to handle the frontend, I am facing a challenge in retrieving data from pages using their ID/Slug since the pages are built with Gutenberg blocks. The issue at hand i ...

Converting a string to JSON format with JavaScript

My string is structured in JSON format like this: "{""c1"": ""value1"", ""c2"": ""value2""}" After storing it in an SQLITE database, I use the following Javascript code to retrieve it back as JSON: var req= "SELECT json_column from my_table"; var re ...

Exploring the ideal scenarios for utilizing propTypes in React

When creating in-house components that require specific props to function properly, I believe it is best to conduct prop requirement checks during testing rather than including propTypes in the production code. This is especially important for components t ...

Show the background color on each list element that is being created from the ng-repeat directive

This code dynamically displays a list of li's with images and text. <ul class="presale"> <li ng-repeat="(k,v) in value | groupBy : 'presales_name'" ng-click="showData(k.split(' ').join('-').r ...

Analyzing the interaction of AngularJS across different pages

I am currently working on an Angular application that consists of a login page and a landing page. My goal is to create a Protractor assertion that can verify the successful login and ensure that the landing page displays correct content. The login proces ...

Guide on accessing a div by using the class name of another div

If I have five divs where the first four share the same class, while the fifth has a different class. How can I target any of the first four divs using the class name present in the fifth div which is labeled as "otherclass" in this scenario? No IDs are ...

Converting JSON date format while deducting one day

JSON is returning the date in this format: /Date(1412101800000)/ However, when I convert it to a normal date format, it ends up being one day less. The code I am using is: var dateFormat = new Date(parseInt(obj['DATEOFJOINING'].substr(6)) ...

server side pagination using ngtable

Hello, I am trying to implement server-side pagination with AngularJS and ngTable. I have two web services: localhost:8080/app/api/period Method GET returns a JSON list of entities. Parameters include the page number, start period range, and end period r ...