Tips for combining values from two inputs to an angular ng-model in AngularJS

I am working with an angular application and I am trying to figure out how to combine values from multiple inputs into one ng-model. Here is an example of my current input:

<input type="text" class="form-control input-md" name="type" ng-model="flat.flatData.type" placeholder="Flat type" >

Although this works perfectly fine, I would like to add more inputs to this model in order to create an array structure. The desired outcome would look something like this:

  • First input value = type1
  • Second input value = type2
  • Third input value = type3

and so on. Ultimately, I want the final array in the model to be [type1, type2, type3]

Answer №1

After some reflection, I realize now what you are trying to achieve. Here is a revised version of the code that I believe addresses your requirements:

html

<div ng-repeat="(key, item) in vm.numbers track by $index">
  <input type="text" ng-model="item" ng-change="vm.updateSum()">
</div>
<button ng-click="vm.addInput()">+</button>
<br><br>
array:
<div>{{vm.numbers}}</div>
sum:
<div>{{vm.sum}}</div>

js:

var vm = this;
vm.numbers = [99,2,3,4,5,6,7,8];
vm.sum = 0;
vm.updateSum = function() {
  for (var i = 0; i < vm.numbers.length; i++) {
    vm.sum = vm.sum + vm.numbers[i];
  }
}
vm.updateSum();

vm.addInput = function(){
  vm.numbers[vm.numbers.length] = 0;
}

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



Prior response:

This scenario lends itself well to utilizing a directive or multiple directives depending on your workflow requirements. A common situation with similar solutions involves validating two fields to ensure they match (e.g., "confirm password" during registration). I suggest exploring that topic further.

In the meantime, simulate the functionality as needed. Here's a plunker demonstrating basic functionality using a $watch:

js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  var vm = this;
  $scope.$watch('vm.one', function() {
    vm.three = parseInt(vm.one) + parseInt(vm.two);
    console.log('one change');
  });
  $scope.$watch('vm.two', function() {
    vm.three = parseInt(vm.one) + parseInt(vm.two);
  });
});

html

<body ng-controller="MainCtrl as vm">
  <input type="text" ng-model="vm.one"><br><br>
  <input type="text" ng-model="vm.two"><br><br>
  <input type="text" ng-model="vm.three">

  <div>{{vm.one}}</div>
  <div>{{vm.two}}</div>
  <div>{{vm.three}}</div>
</body>

http://plnkr.co/edit/8J7X0p?p=info

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

Begin the process of setting up PDF.js on the website

I've been attempting to incorporate PDF.js into my website, but I'm struggling to do it correctly. When I try to display the PDF file on the screen, I encounter this issue: Although I can't see the PDF file on the screen, when I click on P ...

Sorry, but we're unable to provide a unique rewrite of text that is an original error message

Trying to fetch data from a MySQL database using Next.js API routes, I encountered the following error: Error: No response returned from the route handler Below is an example of the code being used: import { NextResponse } from "next/server"; impor ...

How can I transform an HTML element into a textarea using CSS or JavaScript?

While browsing a webpage, I discovered a <div> element with the class .plainMail and I want to find a way to easily select all its text by simply pressing Ctrl+A. Currently using Firefox 22, I am considering converting the div.plainMail into a texta ...

Creating and accessing a temporary binary file using Node Js

Challenge I have been working on integrating the Google Text To Speech (TTS) service to save a generated binary audio file to Google Cloud Storage (GCS). Considering that saving a local binary file in Firebase's Cloud Functions environment may not b ...

URL JSON data will not display markers

I am currently working on a map that fetches data from the police.uk API by allowing users to drag and drop a dot on the map to display crimes within a 1-mile radius. However, I'm facing an issue when trying to implement geocoding functionality by tak ...

When using Express.js for file uploading, it is important to first verify that a file has been sent, set a maximum file size limit, and ensure

After working with expressjs for a month, I've encountered some issues with file uploads. Despite researching on Google and various blogs, I haven't been able to find answers to the following three questions: What do I need to do or what setting ...

What is the best way to retrieve the second element based on its position using a class name in Jquery?

DisablePaginationButton("first"); The statement above successfully disables the first element that is fetched. DisablePaginationButton("second"); ===> not functioning function DisablePaginationButton(position) { $(".pagination a:" + position).ad ...

The async waterfall is encountering a Typeerror due to the nextcallback function not being defined properly

async.waterfall([1,2,3,4].map(function (arrayItem) { return function (lastItemResult, nextCallback) { // performing the same operation for each item in the array var itemResult = (arrayItem+lastItemResult); // pa ...

Dealing with unexpected modifications in a React class component

In short, I need to adjust the data in my class component before sending it to the server to match the API request format. To achieve this, I created a method called transformData within my class component which transforms the data extracted from the state ...

receive the output of the inquiry

Here's the issue I'm facing: file accounts.controlles.ts import { requestT } from "src/service/request.api"; export const getaccounts = async () => { const response = await requestT({ method: "GET", ur ...

Implementing Security Measures for ExpressJS Static File Server

Recently, I set up an authentication system following a tutorial on express.js and passport.js. In the past, my express server setup used modRewrite as shown below: var express = require('express'); var modRewrite = require('connect-mod ...

Having trouble establishing a connection to MySQL through NodeJS and Express

I am currently attempting to establish a connection to MySQL using a nodeJS app with express as the server. I have referred to the mysql npm documentation to start the connection process, but I keep encountering an error in the callback function within cre ...

Is it possible to display partial html templates by accessing the local url and blending them with the main index.html file?

Is there a way to view partial HTML templates locally without copying them into the main index.html file? I'm looking for a solution that allows me to access my partial templates through a local URL without having to manually paste them into the main ...

Adding external JSON data to a plain HTML document can be achieved through the process of

I have been experimenting with extracting data from an API in JSON format, but I am struggling to figure out how to convert the JSON tags into HTML elements. You can view a sample of the JSON data here. Does anyone know how to transform this JSON into DI ...

The HTTP request seems to be malfunctioning

When attempting to establish a connection and retrieve data from a PHP file using an AJAX request, it's important to note that the AJAX JS is located on a different website. Here is the script being used: var quer; try { quer = new XMLHttpRequest( ...

Utilizing a Node.js web server in conjunction with an Apache Cordova Application

I have created an innovative Apache Cordova Application that leverages a Node.js web server to retrieve data from a web API, enabling the JavaScript-based project to utilize the information obtained from the API. Is there a method to integrate this Node w ...

Integrating Python Script with User Input and Output within a JavaScript Web Application

I have an existing JS website that requires additional functionality, and after some research I believe Python is the best tool to handle the necessary calculations. My goal is for users to input information that will then be used as input for my Python ...

Stuck in a rut, the Grunt Serve - express:dev task seems to

I am encountering difficulties with my grunt serve task. It appears to hang when it reaches the express:dev task; Running "express:dev" (express) task Starting background Express server Debugger listening on port 5858 This is an ongoing project where gru ...

Encrypting sensitive information in JavaScript and Angular 2: SecureString

Is there a way to securely copy sensitive data to the clipboard in javascript/Angular2, ensuring that the string remains confidential by removing it from computer memory when no longer needed? In Microsoft .Net, there is a feature called System.Security.S ...

Adjust the clarity of the elements within my HTML document

I have been working on creating a login page that will appear in front of the main webpage. Through my online research, I discovered a technique to blur the main webpage background until the user logs in. Below is the code snippet: HTML: <div id="logi ...