Exploring the power of AngularJS with JSON datasets

While working on angularJS, I encountered a problem with calculating operations on JSON data. I need assistance in solving this issue. enter code hereCode snippet. In the "script.js" file, there is JSON data named "marksArray". My task is to calculate the total marks per student (for example - abc's total marks are 85) and also determine the count of students (separate count like - abc:2 , pqr:2 , xyz:3). Any help in resolving this problem would be greatly appreciated.

Html:

<!DOCTYPE html>

<html>

  <head>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myapp">
    <div ng-controller="mainController">
      <label for="repeatSelect1"> Field 2: </label>
      <select name="repeatSelect1" id="repeatSelect1" ng-model="data.repeatSelect1">
    <option ng-repeat="(key, val) in marksArray[0]" value="{{val}}">{{key}}</option>
  </select>
      <br />
      <strong>Selected student:</strong>
      <br />
      <textarea>{{chosen | json}}</textarea>
      <br />
      <br />
    </div>
  </body>

</html>

Javascript

angular.module('myapp')
.controller("mainController", function ($scope){

    $scope.marksArray = [
      {name: "abc", Marks: "50"},
      {name: "xyz", Marks: "44"},
      {name: "abc", Marks: "35"},
      {name: "xyz", Marks: "55"},
      {name: "pqr", Marks: "67"},
      {name: "xyz", Marks: "65"},
      {name: "pqr", Marks: "45"}
    ];
  });

Answer №1

There are a few mistakes that need to be corrected in your code.

  1. Make sure to include angular.js:

    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="71010e07150c01122e0a1325120d061904">[email protected]</a>" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>

  2. Ensure you declare myapp correctly by using angular.module('myapp',[]) instead of just angular.module('myapp')

  3. Avoid using ng-repeat on options, use ng-options instead. Example:
    <select name="repeatSelect1" ng-options="item as item.name for item in marksArray" id="repeatSelect1" ng-model="chosen"></select>

To display the total of the chosen item, add this function:

$scope.updateTotal = function(item) {
      var total = 0;
      $scope.marksArray.forEach(function(i) {
        if(i.name == item.name){
          total += parseInt(i.Marks,10);
        }
      });
      $scope.total = total;
    }

Check out the plnkr example here

Answer №2

Learn HTML

<!DOCTYPE html>
<html>

<head>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b3a353c2e373a297531281b6a756f7562">[email protected]</a>" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="myapp">
  <div ng-controller="mainController">
    <label for="repeatSelect1"> Student: </label>
    <select name="repeatSelect1" id="repeatSelect1" ng-model="selectedStudent">
      <option value=""> --Choose a student--</option>
      <option ng-repeat="student in students" value="{{student}}">{{student}}</option>
    </select>
    <br />
    <strong>Selected student:</strong> {{selectedStudent || 'no one'}}
    <br />
     <div ng-show="selectedStudent">
       <span>total marks:</span> {{totalMarksPerStudent(selectedStudent)}}  </br>
      <span>student count:</span> {{ totalStudentCount(selectedStudent) }}
     </div>
    <br />
    <br />
  </div>
</body>

</html>

Create Script

angular.module('myapp',[])
.controller("mainController", function ($scope)
  {
    $scope.marksArray = [
      {name: "abc", Marks: "50"},
      {name: "xyz", Marks: "44"},
      {name: "abc", Marks: "35"},
      {name: "xyz", Marks: "55"},
      {name: "pqr", Marks: "67"},
      {name: "xyz", Marks: "65"},
      {name: "pqr", Marks: "45"}
    ];

    $scope.students = [];


    (function(){
      var auxArray = [];
       for (var i = 0; i < $scope.marksArray.length; i++){

           if(typeof auxArray[$scope.marksArray[i].name] === 'undefined'){
                $scope.students.push($scope.marksArray[i].name);
                auxArray[$scope.marksArray[i].name] = 1;
           }
       }
    })();

    $scope.totalMarksPerStudent = function(studentName){
      var marks = 0;

      for (var i = 0; i < $scope.marksArray.length; i++){
         if($scope.marksArray[i].name === studentName){
           marks = marks + parseInt($scope.marksArray[i].Marks);
         }
      }
      return marks
    }

    $scope.totalStudentCount =  function(studentName){
      var studentCount = 0;
      for (var i = 0; i < $scope.marksArray.length; i++){
          if($scope.marksArray[i].name === studentName)
            studentCount++;
      }

      return studentCount
    }
  });

View on Plunker: http://plnkr.co/edit/TEAr9yaf47VlaiYaxBKN

Answer №3

let totalMarks = 0;

$scope.calculateTotalMarks = function(studentName) {
  for (let i = $scope.marksArray.length - 1; i >= 0; i--) {
    if (studentName === $scope.marksArray.name[i]) {
      let totalMarks = totalMarks + $scope.marksArray.Marks[i];
    }
  }
}

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

Troubleshooting: jQuery.load function not functioning properly within ASP.NET MVC

I'm facing an issue with my code setup. Currently, I have the following components in different files: @Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Home/index.html"))) This is included in my Razor file. <li><a href="#">Personal Re ...

After receiving a data token from the server in one controller, how can I efficiently utilize that token in a different AngularJS controller?

In my adminSearchCtrl controller, I am receiving data from the server in the form of a token and want to pass that token to another controller named "adminViewCtrl". How can I achieve this? adminSearchCtrl.js $scope.getUserDetails = function(selectedUser ...

What is the correct method for adding a button to a popup in Leaflet Draw?

I need a button within a popup that can perform an action on the attached layer. L.marker(coors[i], { icon }) .addTo(this.drawnItem) .bindPopup(this._getCustomIcon(mix)) .openPopup(); Here is my _getCustomIcon() function: ...

How to adjust cell alignment in Handsontable

Handsontable showcases cell alignment options in the align cell demo: Horizontal Left Center Right Justify Vertical Top Middle Bottom Displayed below is a screenshot: To retrieve data, utilize the following code snippet: $('#table-wrapper&ap ...

"Launching a node server in Azure to get you up and running

Currently, I have a Single Page Application that is hosted on Microsoft Azure. This application requires refreshing some dashboard data every 5 seconds. To achieve this, I have developed a nodejs service that continuously requests data from the API and gen ...

How can you personalize a website script by deactivating it using uBlock Origin and then reintegrating it as a userscript?

Can you imagine if it were possible to address a problematic portion of a script on a website by preventing the original script from loading, copying the source code, editing it, and then re-injecting it as a userscript with Tampermonkey? I attempted this ...

Getting rid of mysterious Google Analytics script from WordPress

My client has requested that I incorporate Google Analytics into her website. After accessing her Google account, I attempted to paste the tracking code into the appropriate section of the Wordpress plugin. To my surprise, the code did not work as expect ...

Angular - Unable to access property '$invalid' because it is null

Working on my login page with angular and typescript. Clicking the submit button should trigger the login function in the controller, but if the form is invalid, it should just return. New to typescript, I keep running into an error when trying to add an ...

Browserify converts necessary or imported packages into ES2015

Our project involves the use of imports and requires to include various third-party packages via NPM. Some of these packages are written in ES6 and need to be transpiled to ES5/ES2015 for compatibility with browsers like IE11, which do not support the arro ...

Why is my timer function speeding past too swiftly?

My vue.js countdown function is updating too quickly. Displayed below is the data section data() { return { selected: [], countdown: timerLimit } Here is the countdown method countdownTimer() { this.count ...

What is the best method to extract information from an ever-changing external JSON file?

I am currently in the process of developing a discord bot using discord.js, and one of the features I am trying to implement is a command that displays the current bitcoin price. To achieve this, I am utilizing the CoinDesk API which provides the necessary ...

Encountered an issue while trying to send an email through the Gmail API: Unfortunately, this API does not provide

I am attempting to use the Gmail API to send emails. I collect user data and convert it to a base64url string. After obtaining the raw value, I attempt to send the email using a POST request. var ss=new Buffer(message).toString('base64') var ...

Replace character within a table using jQuery

Below is the table content: <table> <tr> <td>"James"</td> <td>"do"</td> <td>"you</td> <td>"like</td> <td>"your life"</td> </tr> </table> <butt ...

Instructions for launching an Ionic project on a mobile device using a PHP backend

I'm curious about how to test my Ionic application with a PHP backend on an Android phone. The database is in phpMyAdmin. Can you help me figure out how to run it and test it on my device? ...

text field remaining populated

I have a form where the input fields clear when they are clicked on. It works well on most pages, but there is a specific type of page where it is not functioning properly due to the presence of another javascript running. - issue observed // On this pa ...

Retrieving the value of a submit button within the `onSubmit` event handler in a React application

In my usual process, I typically handle the form submission by utilizing the onSubmit handler. <form onSubmit={e => { ... } }> <input ... /> <input ... /> <button type="submit">Save</button> </form> ...

Route parameter in JavaScript: only accept numerical values

Is it possible to restrict parameter types to only accept digits? If a letter or other character is inputted, I want to fallback to a default scenario. Below are the two attempts I've made. app.get('/multi/:num?', function (request, respons ...

What is the best way to transfer a segment of CSS, HTML, and JavaScript code from one static template to another?

I have a collection of static files (html, css, and js) and I've identified a specific piece of code (let's say a dinosaur animation) that I want to move to another set of static files (a separate project I'm working on with a different temp ...

Executing a function on page load instead of waiting for user clicks

I've been researching a problem with onclick triggers that are actually triggered during page/window load, but I haven't been able to find a solution yet. What I need is the ID of the latest clicked button, so I tried this: var lastButtonId = ...

jQuery load() function triggers unexpected error in jQuery plugin

Here is the current structure of my page: <body> <div id="menuBar"> </div> <canvas id="myCanvas" width="700" height="700" style="border:1px solid #000000;"></canvas> </body> <script src="../Scripts/jQuery.mazeBo ...