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

What's the optimal method for serializing the `User` model for guest and authenticated users using JSONAPI?

Currently, I am developing an API using express.js following the JSONAPI specification, and utilizing a sequelize.js model. For instance, there is a User model with properties like name, email, balance, last_login_time, etc. When a user requests data abou ...

Trouble with escape sequences in regular expressions within jQuery Terminal for JavaScript

I'm experimenting with special character functionality in jQuery terminal. While I was successful in implementing the backspace functionality, I encountered an issue when trying to execute the escape functionality. Below is the code snippet I used: ...

What is the best way to trigger an event using vue-chartjs?

I am using vue js to display a graph with chartjs. I have implemented an onClick function on the graph to emit an event in the parent component and retrieve data. However, the event is not working as expected. Can you help me identify the issue? Component ...

Guide on altering the background color of a table row depending on the data in its cells with the help of AngularJS

I am looking to dynamically change the background color of a row based on specific cell data. If the first four characters in a table cell match a certain value, I want the entire row to change its color to red. Currently, my code changes the row color ba ...

Working with repeated fields in Google protobuf in JavaScript

Consider this scenario: you have a google protobuf message called Customer with a repeated field as shown below. message Customer { repeated int32 items = 1; } What is the procedure for setting the repeated items field in javascript? ...

Using Jquery to insert error messages that are returned by PHP using JSON

I am attempting to utilize AJAX to submit a form. I send the form to PHP which returns error messages in Json format. Everything works fine if there are no errors. However, if there are errors, I am unable to insert the error message. I am not sure why th ...

Issues with jQuery not detecting click events

Here is an example of HTML: <div class="sortable-buttons"> <ul> <li><a>Recent</a></li> <li><a>Popular</a></li> <li><a>Being Discussed</a></li> </ul> </div ...

Perform an action when a key is held down and when it is released

I am looking to implement a function that needs to be called under certain conditions: It should be triggered every second while a key is being held down (for example, if the key is held down for five seconds, it should fire 5 times every second). If ...

Using AJAX to connect the JSP page with the Servlet's doGet() function for interaction

Currently, I am working on the JAVA code provided below in order to make a call to the servlet's doGet() method from a JSP page using an AJAX request. This is how my AJAX call looks like: I am passing the clicked text captured by ng-click of Ang ...

Create a division that will remain visible on the screen and allow scrolling when a certain class is

Having some trouble with a fixed class div that is not continuing to scroll after the class is removed on scroll. I've attempted to fix this issue but the div keeps getting hidden instead of continuing to scroll. If anyone has any advice or can poin ...

Adjust the text within the paragraph dynamically according to the option chosen in the drop-down menu using

I'm having trouble updating a paragraph in a letter based on the user's selection from a dropdown menu. I can't seem to figure it out. I don't know whether ng-show/hide or ng-options is the best approach for this. I feel completely los ...

How can I remove a quadratic curved arrow tool in Fabric JS canvas after it has been created?

I'm currently working on developing a tool for creating quadratic curved arrows. For reference, I utilized a demo from the following link to build the tool: I have successfully created the tool as per my requirements. However, I am encountering some ...

Why is ng-bind-html not functioning within ng-repeat when ngSanitize is included in the module?

I'm a beginner with AngularJS and I'm trying to bind tags inside an ng-repeat loop, but I've tried using ng-bind-html and ng-bind-html-unsafe without success. The output is not displaying correctly. <script src="https://ajax.googleapis.c ...

Issue with D3: Events not triggering transitions

I am currently working on creating a bar chart using D3 in Angular4. // Enter Phase this.chart.selectAll('.bar') .data(this.barData) .enter() .append('rect') .attr('class', 'bar'); // Update Phase let bars ...

What is the best way to set the length of an undefined item in an object to 0 in reactjs?

I am facing a challenge keeping track of scores within each article and displaying them accurately. The issue arises when there is a missing "up" or "down" item in the object. Below is the data containing all the votes: const votes = { "1": { "up": ...

What could be causing the user object's property in mongoose to appear as undefined?

This is my User Schema: var UserSchema = new Schema ({ username: String, password: String, nativeLanguage: { type: String, default: "English" }, The following route fetches a user object and prints it to the console. ro ...

Tips for building a dynamic navigation menu using AngularJS

Looking to dynamically generate a navigation menu using an angularjs controller: index.html: <body> <div ng-controller="navi"> <ul> <li ng-repeat="nav in navigations"> <a href="{{nav.path ...

Transfer the controller of the parent directive to a directive controller, similar to how it is executed in the "link" function

In the structure of my directives, there is a need for one directive to have functions in its controller so that child elements can interact with it. However, this directive also needs access to its parent directive's controller. I am unsure of how to ...

Which method is better for HTML5/JavaScript GeoLocation: Passing data to a callback function or suspending an async call using promises?

Trying to figure out how to utilize HTML5/Javascript Geolocations effectively for passing location data to an ajax call and storing it in a database. The main challenges I'm facing are the asynchronous nature of the Geolocation call and issues with va ...

Tips for accessing the information received from an AJAX call

When making an AJAX post request for processed data from the database in the form of an array [value1, value2, value3,...,valueN], I aim to use it on a ChartJS object. Here is the AJAX Request: $(document).ready($.post('callMeForAJAX.jsp', func ...