I am requesting for the average to be adjusted based on the user's choice between Hindi or English percentage scale

Currently, the average is being calculated in the HTML code. When a user input is changed, the average breaks. What can be done to update the average for each individual person?

Controller

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope)
{
$scope.names = [
    {name:'Priya',age:'19',gender:'Female',English:x[0], Hindi:x[1]},
    ...
    ...
    {name:'Jiah', age:'18', gender:'Female',English:x[18],Hindi:x[19]}
    ];

$scope.sortColumn ="name";

$scope.$watch('names', function(newVal) {
    var total = 0;
    angular.forEach(newVal, function(x) {
      total += parseInt(x.English) + parseInt(x.Hindi);
    });
    $scope.total = total 
}, true);


$scope.delete = function (name) 
{
    $scope.names.splice( $scope.names.indexOf(name), 1 );
}   
});

HTML This section of code controls where the average should change:

 <table>    
        <th>NAME</th>
        <th>AGE</th>
        <th>GENDER</th>
        <th>ENGLISH/100</th>
        <th>HINDI/100</th>
        <th>AVERAGE/100</th>

    <tr ng-repeat ="x in names | orderBy:sortColumn">
        <td>{{x.name}}</td>
        <td>{{x.age}}</td>
        <td>{{x.gender}}</td>
        <td><input type="text" ng-model="x.English"></td>
        <td><input type="text" ng-model="x.Hindi"></td>
        <td ng-bind="avg=(x.English+x.Hindi)/2">{{avg}}</td>
        <td>
            <button><a href="" ng-click="delete(x)" style="text-decoration:none;">Delete</a></button>
        </td>
    </tr>
</table>

Answer №1

x.English and x.Hindi are being input as strings, so it is necessary to convert them into numerical values.

<td ng-bind="avg=(parseFloat(x.English)+parseFloat(x.Hindi))/2">{{avg}}</td>

Angular expressions do not support JavaScript directly, therefore you must assign a reference to the original function.

$scope.parseFloat = parseFloat;

If needed, an alternative method for conversion is to utilize multiplication.

<td ng-bind="avg=(x.English*1+x.Hindi*1)/2">{{avg}}</td>

Answer №2

To perform calculations in an angular expression, you cannot use the parseInt() function directly. Instead, you must create a custom method to calculate the average.

Invoke the method in the view like this:

<td>{{avg(x.English, x.Hindi)}}</td>

In the controller, define the method that computes and returns the average value:

$scope.avg = function(e, h){
  if(!h) h=0;
  if(!e) e=0;
  return ( parseInt(h)+parseInt(e))/2;

}

You can find a working example on this Plunker.

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 there a way to send me the result of the radio input (Yes/No) via email?

Is it feasible to send the results of a radio input (Yes/No) back to my email directly using HTML, CSS, and Javascript? ...

Looking for assistance in determining a solution for progress bar implementation

Currently, I am developing a simple application using web technologies like HTML, CSS, and jQuery Mobile. This app enables me to create goals and save them to a listview using the <li> element. Every <li> representing a goal will have an assoc ...

Innovative guidelines originating from a resource attribute

I am facing a challenge with a repeater for a resource that has an attribute containing angular directives mixed with text. My goal is to display form inputs dynamically based on the object's property. <ul> <li ng-repeat="action in actions ...

Tips for converting asynchronous function calls into synchronous functions in Node.js or JavaScript?

Imagine you are managing a library that provides access to a function called getData. Users utilize this function to retrieve real data: var output = getData(); In the background, the data is stored in a file, so you have implemented the getData functi ...

What is the best way to implement a swipe gesture functionality in Javascript with Angular Material?

Exploring the potential of utilizing ngMaterial's swipe functionality has sparked my interest, despite encountering a warning... A cautionary note appears as I utilize the ngTouch module. Angular Material already boasts built-in support for mobi ...

angular interceptor is not disapproved

$resource makes an API call. If it receives a certain flag, the request will fall into the .catch() section of $resource('api/').get(...).$promise.catch(); My interceptor doesn't trigger that call. It always calls .then regardless. Interce ...

What is the best way to eliminate spaces in $location.search()?

While using $location.search('event', data);, I've encountered an issue where the URL displays something like this: ?event=arsenal%20fc%20 I am looking to remove these spaces in order to get: arsenalfc ...

Utilize Node.js Socket.IO to trigger CodeIgniter controller function calls

As a beginner with Node.js and socket programming, I am looking to utilize a php function within my nodejs socket program. I am unsure if this is achievable, so any assistance or guidance on how to do so would be greatly appreciated. Thank you in advance ...

using a variable object to load, access data, and handle errors through mutations

element, I have incorporated two distinct mutations in a single react component: const [get_items, { error, loading, data }] = useMutation(GET_ITEMS); const [add_to_cart] = useMutation(ADD_TO_CART); To streamline and access both components' error, ...

Divinely favored - pay attention for each and every sound

Currently, I am utilizing node with the blessed tty library downloaded from NPM. Within this library, there is a method called "key" that I am using in the following way: blessed.key(['q', 'z'], function(ch, key) { //do something ...

Generate a new object from the contents of a div

Having the HTML structure below: <div id="main"> <div id="myDiv1"> <ul> <li>Abc</li> <li>Def</li> </ul> </div> <div id="myDiv2"> <ul> <li>Ghi</l ...

How to Convert Python Lists into JavaScript?

octopusList = {"first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green", "blue", "red"]} squidList = ["first", "second", "third"] for i in range(1): squid = random.choice(squidList) octopus = random. ...

Refresh a TextBox using an Ajax Response

Is there a way to dynamically update a textbox with the response from an ajax call? I've managed to get the response and assign it to the textbox using: document.getElementById("testPad").value = xmlHttpRequest.responseText; The issue is that the en ...

Will it function properly if it is (NULL)?

Here's the code snippet I'm currently using: <html> <head> <link type="text/css" rel="stylesheet" href="html.css" /> <script type="text/javascript"> function getName() { if(name) alert("Did y ...

Transferring an MSAL token to the backend with the help of Axios

I encountered an issue while attempting to send the user ID, which was previously decoded from a JWT token along with user input data. The problem arises when I try to send the data and receive an exception in the backend indicating that the request array ...

Obtaining information from AngularJS callback function in loopback: A comprehensive guide

I am trying to figure out how to retrieve the "good" array from an angular function. Here is the function I have in my Angular code: app.run(function($rootScope,Communications,$http,$filter) { $rootScope.getCommunication = function(object_type ...

Is there a way to connect a Button to a different page in VUE.JS?

I currently have a button that needs to be linked to another page. This is the code I am working with at the moment. How can we write this login functionality in vue.js? It should direct users to the page "/shop/customer/login" <div class="space-x ...

Retrieving Values from Array Objects - Using JavaScript

Discovering the technique to retrieve property values. Given the following: let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}]; How can I output only the value of the second object, which is "website developer"? I am ...

Working with high-resolution images on HTML5 canvas

I am faced with a challenge of incorporating a 15000x15000 px vector image as the backdrop for my canvas project. It is essential to crop specific sections of this image swiftly and consistently, especially within requestAnimationFrame. My current method ...

Converting JSON data into a table using jQuery, with certain columns hidden from view

I am currently working on developing a mobile app using jQuery Mobile and JSON. I have encountered two separate questions: 1) I have a JSON data set which includes fields such as id, name, surname, point, and mail. In my table that lists this data, I init ...