Calculating the Mean of Two selected options in an AngularJS drop-down menu

Is there a way to dynamically calculate the average of two selected values from different select boxes and display the result in a text field without using ng change? Here's an example:

HTML I:

<select ng-model="box1" ng-options="item for item in boxA"></select>

CONTROLLER:

$scope.boxA=[1,2,3,4,5];

HTML II:

<select ng-model="box2" ng-options="item for item in boxB"></select>

CONTROLLER:

$scope.boxA=[6,7,8,9,10];

Text Box:

<input type="text" ng-model="answer">

Answer №1

To avoid using ng-change, one alternative is to create an interval that periodically checks the values in your controller.

$interval(function() {
    if($scope.checkbox1 && $scope.checkbox2) {
      $scope.result =  (parseInt($scope.checkbox1) + parseInt($scope.checkbox2))/2
    }
}, 1000);

Answer №2

If you are looking for a more streamlined approach with Angular, consider using $watchCollection instead:

$scope.$watchCollection('[input1, input2]', function(newValues, oldValues){
    console.log('Input1: '+newValues[0]+', Input2: '+newValues[1]);

    $scope.solution = (parseInt(newValues[0]) + parseInt(newValues[1])/2; //(or adjust 2 to newValues.length if additional models will be added for averaging;)
});

Answer №3

If you want to monitor the values of $scope.box1 and $scope.box2, you can use the following code snippet:

$scope.$watch('box1', function(value){
    $scope.result = calculateAverage(value, $scope.box2);
});
$scope.$watch('box2', function(value){
    $scope.result = calculateAverage(value, $scope.box1);
});

Check out this demo on JSFiddle: http://jsfiddle.net/example-demo/123/

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

Steps for switching back and forth between values within a nested object

In my application, I have developed a custom React hook called useToggles specifically for managing checkboxes and radio buttons. The implementation of this hook typically looks like the code snippet below: const useToggles = (initialValues = {}) => { ...

Why is it that comparing the childNodes of two identical nodes results in false, while comparing their innerHTML yields true?

Currently, I am in the process of developing a simple function in Node.js that compares two DOMs. My goal is to not only identify any differences between them but also pinpoint the exact variance. Interestingly, upon reconstructing identical DOMs using jsd ...

What is the best way to transfer information between two views in Aurelia?

I have two different perspectives, one called logo and the other called folder. The logo view should display something from the folder view if the folder is empty. logo.html <template> <require from="company-assets/folders"></require> ...

Bootstrap modal - Issue with modal automatically closing upon clicking

Trying to send a GET request to the server and use data from the database to populate a modal. The aim is to create an API-like functionality for future efficiency. By assigning the showAjaxModal class to all anchor tags, the goal is to automatically trig ...

Tips for displaying a temporary image placeholder while the actual image loads

One innovative approach is to display a low-resolution version of an image as a placeholder while the high-resolution image loads. This can be achieved using an img tag with specific attributes. <img lowres="http://localhost/low-res-image.jpg" ng-src=" ...

Combining shapes in three.js

I've encountered a scenario where my scene consists of multiple meshes, each with different shapes and sizes. By looping through each mesh and utilizing geometry.merge(), I successfully created a new mesh from the geometries in the scene. The challe ...

What is preventing this Javascript from running in Firefox and Chrome?

I recently encountered an issue with some Javascript code that functions correctly in Internet Explorer, but fails to work on Mozilla Firefox or Google Chrome. Any insights as to why this might be the case? function returnData(strCode,strProgramCode,strNa ...

Having trouble establishing a connection between Node.js server and Google Directions API

Recently, I've been facing an issue while trying to establish a connection with the Google Directions API through my node server using a callback function. Surprisingly, it was working fine just a few days back, and now it seems like I accidentally br ...

How do RxJS collection keys compare?

Is there a more efficient way to compare two arrays in RxJS? Let's say we have two separate arrays of objects. For example: A1: [{ name: 'Sue', age: 25 }, { name: 'Joe', age: 30 }, { name: 'Frank', age: 25 }, { name: & ...

Problem with RadioButton click event not triggering

Among my collection of RadioButton elements, there is an onclick event that should trigger. This event, named SecurityCheckedChanged, will display or hide other div containers (populated with RadioButton elements) based on the selected RadioButton. Howeve ...

See CoffeeScript from the perspective of Compiled JavaScript

https://i.sstatic.net/JRNjG.png I recently started learning Coffeescript and decided to install the 'BetterCoffeeScript' package on Sublime. I am able to see the syntax highlighting, but I'm struggling to view my compiled javascript code. W ...

Incorporating fresh components and newly defined attributes in Angular

Is there a way for me to click on a new component button, specify a name, description, select type, and add attributes such as default value and type? I need all this information to be saved and for the new button to appear in the drag-and-drop section. ...

The function firebase__webpack_imported_module_2__.auth.createuserwithemailandpassword does not exist

I'm facing an issue with my Firebase setup in my code. The browser console is showing that auth.createUserWithEmailAndPassword() is not a function. Can someone help me troubleshoot this problem? Here's the relevant code from login.js import React ...

AngularJS and Bootstrap collaboration creates a stylish oblique design

Can an oblique stripe be made with angularJS and Bootstrap? See image for reference. https://i.stack.imgur.com/v3kEQ.png ...

I am continuously encountering the error message "Resource loading failed" whenever I attempt to launch a React application

I'm currently developing a React App using Webstorm as my IDE. Everything seems to be configured correctly, but whenever I attempt to run the app, I encounter an error message stating "Failed to load resource: the server responded with a status of 404 ...

What is the best approach for re-running controllers once the global data has been resolved?

Upon loading the application, I retrieve data within a run block... .run(function($rootScope, $q, teams, schools, news, games){ // Fetch all relevant data $rootScope.showSplash = true; $q.all([ $rootScope.school = schools.get({id:1}), $root ...

Ways to choose a designated element without relying on ids or classes

I am looking to create an on-click function for each button, so I require a method to select each one individually without relying on IDs <div class="col"> <div> <b>Name:</b> <span ...

Adding a class in Javascript if its parent element already has a class

I am trying to assign a second class to a div if one of its parent elements has a specific class. Here is the approach I took: var elements = document.querySelectorAll('h1,h2,h3,h4,p'); //SELECT ALL ELEMENTS for (var i = 0; i < elements.lengt ...

Secure your JavaScript file with encryption

I am curious if anyone has ever used a tool to protect and fully encrypt JavaScript files. I recently came across a tool that claims to be able to completely encrypt JS files. Have you heard of this before? What are your thoughts on it? ? ...

The image will only display upon receiving a link, not a path

Having some trouble displaying an image on my website, despite having successfully done so in the past for other projects. The image is located in the same folder as my HTML file. Here's what I've tried: <img src="reddit.png"/> <img s ...