AngularJS script to dynamically update a table upon selecting an option from the dropdown menu

Just starting out with Angularjs and facing a challenge. I have a table with a "Update" button on the UI and a drop-down option in the 3rd column. The requirement is, upon selecting an option from the drop-down and clicking the "Update" button, the values in columns 4 and 5 of the table should be updated with calculated values based on the chosen modelId and formula.

I've shared the code below. Need assistance with implementing the drop-down and the JavaScript function to update the values upon clicking the update button.

For clarity, I have included an image below:

enter image description here

enter code here

<!DOCTYPE html>
  <html ng-app="myApp">

  <head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e2838c85978e8390cc8891a2d3ccd6cc9a">[email protected]</a>" 
  src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"> 
    </script>
    <script src="script.js"></script>
    <link 
     href=
    "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" 
     type='text/css' rel="stylesheet">
     <link rel="stylesheet" type="text/css" href="style.css">
     </head>

     <body ng-controller="MainCtrl">
     <div class="row">
    <div class='col-sm-12'>
      <div class="form-group" style="padding-left:15px">
           <div>
            <input type="button" value="Update"  ng-click="update()" 
     class="btn btn-primary" />
          </div>
        </div>
      </div>
       </div>
     <div class="row">
      <div class='col-sm-12'>
      <table class="table table-striped table-bordered">
        <thead>
          <tr>
            <th>Model ID</th>
            <th>MRS</th>
            <th>Formula</th>
            <th>Score1/th>
            <th>Score2</th>
          </tr>
        </thead>
        <tbody>
          <tr ng-repeat="model in models" ng-model="model">
            <td>{{model.modelid}}</td>
            <td>{{model.mrs}}</td>
            <td>{{model.formula}}</td>
            <td>{{model.score1}}</td>
            <td>{{model.score2}}</td>
          </tr>
         </tbody>
         </table>
       </div>

      </div>
      </body>
      <script>
     app.controller('MainCtrl', ['$scope','$filter', function ($scope, 
    $filter){

     $scope.models = [
    { id: 1, 'modelid': 'model1', 'mrs': 'high', 'score 1':'2.4' ,'score 
     2':'28.4'},
    { id: 2, 'modelid': 'model2', 'mrs': 'low',  'score 1':'20.6','score 
      2':'45.4'},   
    { id: 3, 'modelid': 'model3', 'mrs': 'medium', 'score 1':'34','score 
       2':'9.4'}
        ];
         $scope.update = function() {

        };
        </script>  
         </html>

Answer №1

Hey there! I've made some adjustments to the javascript code to better fit your needs. I'm fairly new to angularjs, but it reminds me a bit of knockoutjs with its computed variables and automatic updates. In knockoutjs, everything just updates on its own without the need for an update button. However, angularjs does seem a bit more complex to me.

Regarding your specific issue, I inputted some random values since I wasn't sure about the equation you were looking for. Hopefully, this gives you a good starting point and understanding of the fundamentals.

<!DOCTYPE html>
  <html ng-app="myApp">

  <head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8cede2ebf9e0edfea2e6ffccbda2b8a2f4">[email protected]</a>" 
  src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"> 
    </script>
    <link 
     href=
    "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" 
     type='text/css' rel="stylesheet">
     <link rel="stylesheet" type="text/css" href="style.css">
     </head>

     <body ng-controller="MainCtrl">
     <div class="row">
    <div class='col-sm-12'>
      <div class="form-group" style="padding-left:15px">
           <div>
            <input type="button" value="Update"  ng-click="update()" 
     class="btn btn-primary" />
          </div>
        </div>
      </div>
       </div>
     <div class="row">
      <div class='col-sm-12'>
      <table class="table table-striped table-bordered">
        <thead>
          <tr>
            <th>Model ID</th>
            <th>MRS</th>
            <th>Formula</th>
            <th>Score1</th>
            <th>Score2</th>
          </tr>
        </thead>
        <tbody>
          <tr ng-repeat="model in models" ng-model="model">
            <td>{{model.modelid}}</td>
            <td>{{model.mrs}}</td>
            <td><select ng-model="model.formula" ng-options="x for x in formulas"></select></td>
            <td>{{model.score1}}</td>
            <td>{{model.score2}}</td>
          </tr>
         </tbody>
         </table>
       </div>

      </div>
      </body>
      <script>
      var app = angular.module('myApp', []);

     app.controller('MainCtrl', ['$scope','$filter', function ($scope, $filter){

        $scope.formulas = ["Forumula 1", "Forumula 2", "Forumula 3"];





        $scope.models = [
            { id: 1, 'modelid': 'model1', 'formula':'', 'mrs': 'high', 'score1':'2.4' ,'score2':'28.4', },
            { id: 2, 'modelid': 'model2', 'formula':'', 'mrs': 'low',  'score1':'20.6','score2':'45.4'},   
            { id: 3, 'modelid': 'model3', 'formula':'', 'mrs': 'medium','score1':'34','score2':'9.4'}
        ];
        $scope.update = function() {

            for(var i = 0;i<$scope.models.length;i++) {

                if($scope.models[i].formula == "Forumula 1") {

                    $scope.models[i].score1 = Math.floor((Math.random() * 100) + 1) * Math.floor((Math.random() * 100) + 1);
                    $scope.models[i].score2 = Math.floor((Math.random() * 100) + 1) * Math.floor((Math.random() * 100) + 1);

                }
                else if($scope.models[i].formula == "Forumula 2") {

                    $scope.models[i].score1 = Math.floor((Math.random() * 100) + 1) 
                    $scope.models[i].score2 = Math.floor((Math.random() * 100) + 1) 

                }
                else if($scope.models[i].formula == "Forumula 3") {

                    $scope.models[i].score1 = Math.floor((Math.random() * 10) + 1) 
                    $scope.models[i].score2 = Math.floor((Math.random() * 10) + 1) 

                }

            }

        }

        }]);
        </script>  
         </html>

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

Creating a service in AngularJS 1.8 with ES6 modules that acts as a bridge to a class based API interface

As I continue to enhance a codebase that originally consisted of a mix of different versions of AngularJs and some unstructured code utilizing various versions of a software API, I encounter an interesting quirk. It appears that this API is accessible thro ...

Unable to access CommonModule in Angular 10 component loaded dynamically

I'm currently working on a project using Angular. One of my methods involves dynamically creating a component, but I'm encountering difficulties when trying to use directives like ngClass and ngIf from the CommonModule within this component. Her ...

When viewing on smaller devices, columns in Bootstrap will have varying height ratios except for the 1:1 ratio

Initially, I was unsure about the kind of research I needed to conduct, which led me to asking a potentially duplicate question. Nevertheless, the code I am working with is quite simple: #my-container { height: 100vh; } <link rel="stylesheet" hr ...

Retrieve information from a PHP file using AJAX when the output is just a single line

I never thought I would find myself in this situation, but here I am, stuck. I just need a single result from this PHP file, so is using an array really necessary? Despite my efforts to console.log(result) multiple times, all I get back is "null". What c ...

What is the best way to align the 5th and 6th list items to the left using CSS?

I am experimenting with Bootstrap to create a customized navbar. I am encountering difficulties in aligning the login and logout buttons to the right. Is there a way to achieve this? I have included my HTML and CSS code below: HTML code: <body> &l ...

Do the items appear on screen only once you start typing in AngularJS?

Most things are working well except for a couple of issues Code var app = angular.module("MyApp", []); app.filter('offset', function() { return function(input, start) { start = parseInt(start, 10); return input.slice(start); }; } ...

In the ajax call, an empty JSON array object is sent as the data

Utilizing JSON data as a parameter for an ajax call: var startDate = dateFormatForSave($("#start_date").val().trim()); var arrayOfStudentsInfo = []; var table = $("#selected_students"); table.find('tr').each(function(i, el) { var rowId = $( ...

Instructions on filling the star icon with color upon clicking the button

Currently working on a project using codeIgniter where I have a form for rating products. I am facing an issue where, upon clicking the star button, only the border color changes to yellow while the center of the button remains white. Can someone please g ...

The date picker feature of Jquery Mobile is not appearing on the popup field

I implemented the jtsage jquery mobile date picker, and I am facing an issue where the date picker appears behind the popup instead of in front of it when the text inside the popup is clicked. Here is a snippet of my code: <div data-role="content"> ...

Is it possible to return PHP parser errors as JSON data?

I am facing an issue with my HTML page that uses a JQuery Ajax call to communicate with a PHP page and expects a JSON response. If the PHP encounters a parser error, it sends back the error message but not in the expected JSON format. This leads to a "JSON ...

Drawing intersecting lines on a javascript canvas and clearing them using the lineto method

I am working with a canvas where lines are drawn based on mouse movement. I am trying to achieve the effect of the line only lasting for a few seconds before disappearing, similar to swirling a ribbon with a set length. I have been using lineTo to draw the ...

In JavaScript, the return statement is used to halt the execution of any subsequent statements

I encountered a situation where I need to stop the execution of the next function call if the previous function has a return statement. However, I noticed that even though there is a return statement in the "b" function below, the next function call still ...

A guide to dynamically loading a new page in AngularJS as a user begins typing in an input field

On my website, the /search route displays a Template along with its related Controller, showcasing a list of entries fetched from the database. This is achieved by properly binding data from the Controller to the Template using the $scope variable. When I ...

The requested 'Pagination' component (imported as 'Pagination') could not be located within the 'swiper' library. Possible exports include Swiper and default

I was trying to implement pagination using swiper. I included the Pagination module with this import statement: import { Pagination } from "swiper"; Here's my configuration: https://i.sstatic.net/1iqoi.png The error that I encounter ...

Complete Search with the press of Enter on the Auto Textbox

I have implemented an Ajax auto complete extender on a TextBox control. As the user begins typing, suggestive options are displayed below the input field based on data retrieved from a webservice call. When OnClientItemSelected="GetCode" is triggered, the ...

Combine several JSON files into a single file

After spending countless hours searching on Google, I finally gathered the courage to ask my question here. I have several json files. localhost/feed01.json localhost/feed02.json localhost/feed03.json All of the json file structures are similar to this ...

Use JavaScript to create a new window and load the HTML content from an external URL

Just starting out with HTML and Javascript I'm trying to use JavaScript to open a window and load content from an external source. I attempted using document.write(), but it only works when I hardcode the HTML as input. Any suggestions on how to get ...

Prevent the occurrence of endless looping in serializer (angularjs) by avoiding infinite recursion

Currently, I am working on a RESTful application that involves @OneToMany relationships. The entities in question are Team and Player (where one Team can have many Players, and each Player belongs to only one Team). To prevent infinite recursion, I decid ...

Is there a way to show a fallback message for unsupported video file formats?

When incorporating a video element on my webpage, I typically use the following code: <video src="some source" controls> Error message </video> Based on my knowledge, the "Error message" will only appear if the browser does not support the ...

The submit button seems to be unresponsive or unreactive

As a newcomer to Angular 2 and Typescript, I am in the process of building a web application. I have created several input fields and, following user submission via a button, I want to log the inputs to the console. However, it seems like my button is not ...