Displaying a Div element containing dynamically calculated values based on selected options in Angular

As a newcomer to Angular, I decided to challenge myself by building a simple app. Currently, my select options only display the keys of a data object. What I really want to achieve is to show a value beneath the second select box for each team, which displays the associated value with the key when the first option is selected, and then adds to that value when the second option is selected. How can I accomplish this in Angular?

<div>Team 1</div>
<br> Player 1:
<select class="form-control" ng-model="selectedItem1">
    <option ng-repeat="(k,v) in data.playerInfo">{{k}}</option>
</select>
Player 2:
<select class="form-control" ng-model="selectedItem2">
    <option ng-repeat="(k,v) in data.playerInfo">{{k}}</option>
</select>
<!-- show value here -->
<br>
<br>
<br>
<div>Team 2</div>
<br> Player 1:
<select class="form-control" ng-model="selectedItem3">
    <option ng-repeat="(k,v) in data.playerInfo">{{k}}</option>
</select>Player 2:
<select class="form-control" ng-model="selectedItem4">
    <option ng-repeat="(k,v) in data.playerInfo">{{k}}</option>
</select>
<!-- show value here -->
<div ng-show="k == v">{{v}}</div>

The values need to be displayed under the Team 2 boxes.

UPDATE: I found a solution that worked perfectly for me!

$scope.calc = function() {
        $scope.calculatedValue = Number($scope.selectedItem1);
        if($scope.selectedItem2){
                $scope.calculatedValue = Number($scope.selectedItem1) + Number($scope.selectedItem2);

        }

    }

    $scope.calc2 = function() {
        $scope.calculatedValue2 = Number($scope.selectedItem3);
        if ($scope.selectedItem4) {

        $scope.calculatedValue2 = Number($scope.selectedItem3) + Number($scope.selectedItem4);
        };

    }

<div>Team 1</div>
    <br> Player 1:
    <select class="form-control" ng-model="selectedItem1" ng-change="calc()">
        <option ng-repeat="(k,v) in data.playerInfo" ng-value="v" >{{k}}</option>
    </select>
    Player 2:
    <select class="form-control" ng-model="selectedItem2" ng-change="calc()">
        <option ng-repeat="(k,v) in data.playerInfo" ng-value="v">{{k}}</option>
    </select>
    <!-- show value here -->
    <p> Total Value: {{calculatedValue}} </p>
    <br>
    <br>
    <br>
    <div>Team 2</div>
    <br> Player 1:
    <select class="form-control" ng-model="selectedItem3" ng-change="calc2()">
        <option ng-repeat="(k,v) in data.playerInfo" ng-value="v" >{{k}}</option>
    </select>Player 2:
    <select class="form-control" ng-model="selectedItem4" ng-change="calc2()">
        <option ng-repeat="(k,v) in data.playerInfo" ng-value="v">{{k}}</option>
    </select>
    <!-- show value here -->
    <p> Total Value: {{calculatedValue2}} </p>

Answer №1

I have created a fiddle using your example as a reference. In order for the controller to calculate values and store them in a new property on $scope, you will need to add a change event to the select forms.

HTML

 <select class="form-control" ng-model="selectedItem1" ng-change="calc()">
    <option ng-repeat="(k,v) in data.playerInfo" ng-value="v">{{k}}</option>
</select>

JS

// Initialize default number values
$scope.selectedItem1 = 0;
$scope.selectedItem2 = 0;

$scope.data = {
    playerInfo : {
        a:1,
        b:2,
        c:3
    }
};

// Function to calculate the value
$scope.calc = function(){
    $scope.calculatedValue = parseFloat($scope.selectedItem1) + parseFloat($scope.selectedItem2);
}

It is important to set default values for selectedItem1 and selectedItem2 so that the change event can handle non-numeric undefined values of unchanged selects.

Check out this live demonstration based on your code: https://jsfiddle.net/gu9fm5xh/1/

Answer №2

There are a couple of things to consider:

First: It's generally recommended to use ng-options on the select element instead of using ng-repeat in options. Although it's not a major issue, using ng-options can provide better control.

<select class="form-control" ng-options="data.displayValue for data in data.playerInfo" ng-model="selectedItem4">

This code will display "data.displayValue" in the select box, which can be any property from the playerInfo object. It will also set selectedItem4 to the actual data object.

Second: In the div, you are using k and v variables from your ng-repeat. Remember, each ng-repeat creates its own scope, so the scope variables k and v are not accessible outside of the repeat. If you need to use the selected values outside of the ng-repeat, you should set them to a scope variable. Fortunately, with the option tag, you can achieve this by setting the value field.

<option ng-repeat="(k,v) in data.playerInfo" ng-value="v">{{k}}</option>

Behind the scenes, ng-options handles this for you. This setup binds your select's ng-model to the current option being displayed. So, when an option is selected, selectedItem4 will be set to the value of that option.

<select class="form-control" ng-model="selectedItem4">

Therefore, if you update your div like this:

<div >{{selectedItem4}}</div>

It should work more effectively.

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

Is it possible to have the cursor rotate or animate by 45 degrees when clicked

Do you know how to create a unique custom cursor using CSS? Say, for example, we have this code: cursor: url(images/cursor.png) 15 15, auto; Now, what if we wanted to take it up a notch and make the cursor rotate -45 degrees when clicked, and then revert ...

Incorporating an HTTP header into d3.json using queue.js

I know that I can include a header in a D3 JSON request by using the following code: d3.json("http://localhost:8080/data") .header("Application-ID", "1") However, I'm uncertain about how to add this header when utilizing queue's defer method. ...

Discovering the corresponding elements within an array of objects

Within my array of objects, I am performing a search let arr = [ { name:"string 1", arrayWithvalue:"1,2", other: "that" }, { name:"string 2", arrayWithvalue:"2", other: "that" }, { name:"string 2", arrayWithvalue:"2,3", other: "that" }, ...

Challenges with Hangman in JavaScript

As a beginner in JavaScript, I recently developed a simple hangman-like game. However, I encountered some challenges that I need help with. One issue is related to my lettersGuessed array. Currently, the array displays every time a key is pressed and repea ...

How to retrieve a form submission from Jquery HandsonTable in PHP using $_POST

Recently, I've started diving into the world of javascript/jquery/ajax. My current project involves fetching data from a jQuery handsonTable () and integrating it with my PHP code. The process includes generating a table from a MySQL database, utili ...

What are the best practices for creating a contemporary website that functions effectively on IE7?

After creating several websites for my clients, I discovered that they are not functioning well in IE7. Unfortunately, there is still a small percentage of people using IE7. Can anyone suggest a super quick solution to fix this issue? Feel free to recomm ...

What is the best way to transform a Map<string, boolean> into an array of objects with key-value pairs {key: string, value: boolean

I'm currently working on a React project that incorporates TypeScript, and I've successfully implemented dynamic permission creation on the user creation page by utilizing this particular code snippet. The permissions being used on the page are m ...

Angular 7 three-dimensional model display technology

Looking for advice on creating a 3D model viewer within an Angular 7 project. Currently using the model-viewer web component in JavaScript with success. How can I replicate this functionality and viewer within my Angular 7 application? ...

The JavaScript animations in AngularJS using ng-class are not being activated

I've been attempting to apply js-defined animations to the ng-class directive using the standard syntax of add and remove, but for some reason, the animations are not running. After checking the logs, it seems that the add and remove functions are not ...

Switch from using pure JavaScript to jQuery or back

While I can navigate through jquery, javascript is a bit more challenging for me. I have a simple function that's coded in javascript, but I need to update the selectors. Changing them in jquery wouldn't be a problem for me, but it's tricki ...

What could be the reason for the three.js scene failing to render in my Svelte application?

Scene.svelte <!-- Start by binding a container, then add the renderer to this container onMount --> <script> import { onMount } from 'svelte'; import * as THREE from 'three'; let container; onMount(async () = ...

How can I retrieve the content from an iframe whenever its state is altered using jQuery?

I am currently working on a project where I need to extract the content from a hidden iframe and display it as HTML in a div every time the iframe changes its loading state. The goal is for it to appear as if the page is being redirected and downloading it ...

Using jQuery to clear a textarea when a select input is changed

Currently, I am in the process of developing a small text editor that enables users to edit files and create new ones. Here is how I have set up my select menu. <select name="reportname" id="reportname" class="form-control"> <option value="zr ...

Use jQuery to update the field without affecting the observable

Greetings to the wonderful stackoverflow community! I recently delved into using knockout just a few days back. Currently, I am utilizing it to create a dynamic menu builder for a CMS project that I'm deeply engrossed in. If you'd like to take ...

Having trouble with the alias in commander.js not functioning as desired when using the "--help" option

Currently, I am facing a strange issue while working on my project with commander.js. The problem arises when assigning an alias for a command. I looked at some examples mentioned in the reference: Commander.JS Example I decided to create a git-like comma ...

Validation of Email Existence (Using Django and Javascript/Ajax)

I'm currently facing a challenge with building an E-mail validator using Django and Javascript/Ajax. Despite my efforts, I seem to be stuck at a certain point where the Ajax response consistently shows: {response: "This field is required.", email: fa ...

Node.js equivalent of Java's byteArray

I have a Node.js REST API with images being sent from a Java application as byte arrays. Here is an image Below is the string representation of the image in byte array form: [B@c75af72 I need to decode this byte array to verify if it is indeed an ima ...

Are there any tools available to eliminate the need for inline annotation injection in the Rails Asset Pipeline when using AngularJS?

I am currently working on a Rails + AngularJS project without using inline annotation injection and relying on gulp-ngcompile to compile my scripts. However, I'm considering switching from gulp to the asset pipeline. Can anyone recommend any asset pip ...

Understanding the readability of JavaScript arrays.ORDeciphering

Recently, I've been working with a JSON OBJECT that looks something like this { "kay1": "value1", "key2": "value2", "key3":{ "key31": "value31", "key32": "value32", "key33": "value33" } } However, I am interested in converting it ...

Unable to generate a fresh directory with mongoose and express

As the title suggests, I am working on an application that generates a link using mongoose _id and express's app.get when certain information is inputted. However, I am facing an issue where I have to reload the entire server in order to access the di ...