Is there a way to extract two values from an array and pass them as arguments to a new function within an AngularJS controller?

Exploring the realm of web development, I recently embarked on my journey with the MEAN stack. Facing a seemingly straightforward question that has left me stumped, I turned to various resources for answers without much luck. So, here I am, reaching out in hopes of cracking this puzzle.

In essence, what I aim to achieve is:

  • Extract multiple values from an array
  • Integrate these fetched values into a new scope
  • Handle all operations within the controller to facilitate posting of all values, including the freshly added one, to my database (mongo).

The desired scenario involves extracting and combining the values as follows:

index = value[0]*weight[0] + value[1]*weight[1].... and so forth 

Within my Angular controller lies the following code snippet:

 $scope.alerts = [
    { title: 'someTitle1',
      weighttitle: 'someweightTitle1',
      value: 1,
      weight: 30,
      options: {
        showTicks: true,
        hidePointerLabels: true,
        hideLimitLabels: true,
        stepsArray: [
            { value: 1, legend: 'Very poor' },
            { value: 2, legend: 'Very poor' },
            { value: 3, legend: 'Fair' },
            { value: 4, legend: 'Very poor' },
            { value: 5, legend: 'Average' }

        ]
      }
    },
    { title: 'someTitle2',
      weighttitle: 'someweightTitle2',
      value: 1,
      weight: 60,
      options: {
        showTicks: true,
        hidePointerLabels: true,
        hideLimitLabels: true,
        stepsArray: [
            { value: 1, legend: 'Very poor' },
            { value: 2, legend: 'Very poor' },
            { value: 3, legend: 'Fair' },
            { value: 4, legend: 'Very poor' },
            { value: 5, legend: 'Average' }

        ]
      }
    }
];

I attempted a solution along the lines of:

$scope.index = alert.value*alert.weight

However, my attempts fell short. At this juncture, I find myself at a loss on how to retrieve these values effectively. Perhaps my grasp of the underlying concept is slightly off the mark.

I would greatly appreciate any guidance offered!

While previous solutions did yield results, they lacked dynamic adjustments. The HTML structure pertaining to this issue is depicted below:

<section ng-controller="ArticlesController">
  <div class="page-header">
    <h1>Neue Evaluierung</h1>
  </div>
  <div class="col-md-12">
    <form name="articleForm" class="form-horizontal" ng-submit="create(articleForm.$valid)" novalidate>
      <fieldset>

        <div class="row form-group">
         <h3>Projekttitel</h3><input type="submit" class="btn btn-default btn-lg btn-success">
        </div>
        <div ng-show="error" class="text-danger">
          <strong ng-bind="error"></strong>
        </div>

        <input name="title" type="text" ng-model="title" id="title" class="form-control">

        <div ng-repeat="alert in alerts">

          <h3>{{alert.someTitle}}</h3>
          <input type="number" ng-model="alert.value"/>

          <div>
            <rzslider rz-slider-model="alert.value"
                      rz-slider-options="alert.options"></rzslider>
          </div>

          <br>
          <br>
          <br>
          <br>

          <div>
            <h4>{{alert.someweightTitle}}</h4>
            <input type="number" ng-model="alert.weight"/>
            <div>
              <md-slider flex md-discrete ng-model="alert.weight" step="1" min="1" max="100" aria-label="rating"></md-slider>
            </div>
          </div>

          <input type="number" ng-model="index"/>
          <input type="number" ng-model="indexdynamic"/>

        </div>


      </fieldset>
    </form>
  </div>
</section>

Answer №1

UPDATE:

The following code snippet demonstrates how to display the items in an ng-repeat loop from your alerts array along with their calculated index. Additionally, it includes a form that allows users to add new items to the alerts array and calculate their respective index.

Feel free to experiment with this functionality on this Fiddle.


HTML code

<section ng-controller="ArticlesController">
  <div class="col-md-12">
    <div ng-repeat="alert in alerts">
      <strong>{{alert.title}}</strong>: {{alert.value}}
      <br/>
      <strong>{{alert.weighttitle}}</strong>: {{alert.weight}}
      <br/>
      <strong>Index:</strong> {{alert.index}}<br/><br/>
    </div>
    <form>
      <h1>Add an alert</h1>
      Title:<input type="text" ng-model="new.title"/><br/>
      Value:<input type="text" ng-model="new.value"/><br/>
      Weight title:<input type="text" ng-model="new.weighttitle"/><br/>
      Weight:<input type="text" ng-model="new.weight"/><br/>
      Index: {{new.value * new.weight}}<br/>
      <button type="submit" ng-click="create()">Add this!</button>
    </form>
  </div>
</section>

AngularJS code

var myApp = angular.module('myApp', []);

function ArticlesController($scope) {
  $scope.new = {};

  $scope.alerts = [
      { title: 'someTitle1',
        weighttitle: 'someweightTitle1',
        value: 1,
        weight: 30,
        options: {
          showTicks: true,
          hidePointerLabels: true,
          hideLimitLabels: true,
          stepsArray: [
              { value: 1, legend: 'Very poor' },
              { value: 2, legend: 'Very poor' },
              { value: 3, legend: 'Fair' },
              { value: 4, legend: 'Very poor' },
              { value: 5, legend: 'Average' }

          ]
        }
      },
      { title: 'someTitle2',
        weighttitle: 'someweightTitle2',
        value: 1,
        weight: 60,
        options: {
          showTicks: true,
          hidePointerLabels: true,
          hideLimitLabels: true,
          stepsArray: [
              { value: 1, legend: 'Very poor' },
              { value: 2, legend: 'Very poor' },
              { value: 3, legend: 'Fair' },
              { value: 4, legend: 'Very poor' },
              { value: 5, legend: 'Average' }
          ]
        }
      }
  ];

  for(var i = 0; i < $scope.alerts.length; i++) {
    // Add value * weight to index
    $scope.alerts[i].index = $scope.alerts[i].value * $scope.alerts[i].weight;
  }

  $scope.create = function() {
      // Calculate index
      $scope.new.index = $scope.new.value * $scope.new.weight;
      // Add it to the array
      $scope.alerts.push(JSON.parse(JSON.stringify($scope.new)));
  }
}

Answer №2

To utilize the reduce method, follow this example:

var data = [
    { name: 'item1',
      price: 10,
      quantity: 2
    },
    { name: 'item2',
      price: 20,
      quantity: 3
    }
];

var totalCost = data.reduce(function(prev, next) {
  return prev + (next.price * next.quantity);  
}, 0);

console.log(totalCost); // 70

Remember to save the final result in your designated scope. The snippet above omits the scope for simplicity as it is irrelevant to the reduce function.

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: Issue with onclick event in vue.js/bootstrap - encountering error message "Variable updateDocument not found"

As a newcomer to frontend development, I have a basic understanding of HTML5, CSS, and Javascript. Recently, I started working on a vue.js project where I integrated bootstrap and axios. Everything seemed to be working fine until I encountered an issue whe ...

Seeking to duplicate script for a new table without making any changes to the original script

I am working with two tables that require the capability to dynamically add and delete rows using separate scripts. How can I modify the second script so that it only affects the second table and not the first one? Table: <table id="myTable" class=" t ...

Display a few HTML elements sourced from a different online platform

I am trying to extract a specific value from a span element on another website and render it on my own website using either a GET/FETCH request or some other method. Currently, I have this code but I am struggling to extract the data I need. The data I am ...

Adding new elements to an array does not activate the reactivity of Vue

After discovering that editing objects within an array doesn't function properly in vue.js due to its limitations, I tried using vue.set to resolve the issue, but it's proving to be quite challenging for me. Let's take a look at the sample ...

What is the solution to prevent expressJS routes from displaying "cannot get /somepath" in the browser?

I've been working on a project using React, and I'm trying to create a unique route in the front end without having to create a separate HTML file for each new route. I want everything to be handled within a single page to maintain the current st ...

Vue js has a feature that enables users to input numbers with precision up to two decimal places

Currently facing an issue where I need to restrict input to no more than 2 decimal places. I came across a solution in a thread on Stack Overflow which addresses this using jQuery: JQuery allow only two numbers after decimal point. However, I am looking ...

{reloadOnSearch: false} controller remains stationary when navigating back through history

I am currently working on a controller located at /page with {reloadOnSearch: false}. Upon initialization, it modifies the URL as follows: var query = $location.search(); if (!query.tab) { $location.search('tab', 'tab1'); } Howeve ...

Dynamically generate a new array every time a numeral is encountered within the Input Array in JavaScript

I'm facing a dilemma. I have an array with user input that contains both numbers and strings, like this:- 3 apple Lemmon sugar 2 Ginger Ice This is the data I'm working with. My task is to manipulate the data so that "Whenever it encounters a n ...

Transfer the scroll top value from a textarea to a div element

In the parent div, there is a div and a textarea. I am attempting to synchronize the scrollTop value of the textarea with the div so that they move together when scrolling. The issue arises when I input text into the textarea and hit enter for a new line. ...

Trouble uploading an audio blob as a base64 string using Google Drive API with the drive.files.create method - File ID could not be located

My current challenge involves sending an audio blob to a specific Google Drive folder. To accomplish this, I convert the blob into a file before initiating the transfer process. However, I have encountered an error from the beginning: Error: File not fo ...

Swapping out the entire vue.js container

I have a custom vue.js widget that I initialize like so: var myWidget = new Vue({ el: '#widget-container', methods: { loadData:function() { // custom functionality here } }, }); The HTML structure is as f ...

Streaming videos using Flask with a custom template

After successfully implementing the DWA path planning algorithm in C with Python bindings, I have decided to create a web application demo. The concept involves a "robot" following the mouse using DWA, while allowing users to draw walls for objects. My ini ...

What is the best way to connect the button value with my ng-model data?

I'm having trouble getting the button value to bind to my ng-model. Any suggestions on how I should approach this? Currently, I am utilizing the datepicker from https://github.com/rajeshwarpatlolla/ionic-datepicker <div class="col"> <labe ...

Is there a way to efficiently parse HTML data returned as JSON in the browser using Cordova/Ionic?

Currently, I am retrieving data from a Drupal service and using AngularJS along with the ionic framework to create a hybrid app for mobile platforms, leveraging Cordova or Phonegap. You can check out my code on codepen: http://codepen.io/BruceWhealtonSWE/p ...

What is the reason for $(this) being appropriately recognized for click events but not for hover actions?

Why does this work on an element-by-element basis? <script> $(document).ready(function(){ $("p").click(function(){ $(this).hide(); }); }); </script> </head> <body> <p>If you click on me, I will disappear.</p> &l ...

Error 405 (Method Not Permitted)

Just starting out with AngularJs and Ionic. Creating a schedule app as a learning exercise, so please bear with me. I'm puzzled by this 405 response I'm receiving. When I tested the GET request in Postman using the same data, it worked fine. How ...

Increase value of field in subdocument of Mongoose if it already exists, otherwise create a new subdocument

My Goal and Query In my project, I have a data structure called userSchema, which includes an array of operationCountSchema objects. My objective is to write a static method that can update the count field in one of these operation count subdocuments base ...

Unable to connect with controller after deploying asp.net mvc ajax call on server

For the first time, I am encountering a new issue. Although my code runs smoothly on my localhost, when I upload it to the server, I get a bad request error. The specific error message is: 400 (Bad Request) Below is the snippet of my code: Controll ...

Traverse through the city IDs in Openweathermap to retrieve the latest weather conditions

In my database, I have a list of cities along with their corresponding city IDs. My goal is to iterate through these cities and retrieve the current weather for each city, storing the results in an array using Axios. Here's what I've attempted: c ...

Querying with complex aggregations in MongoDB for sorting operations

Can anyone help me with sorting a list of accommodations based on price and number of amenities they offer? The main challenges are converting the price (which is in string format starting with $) to an integer for proper sorting, and determining the cou ...