Discover the smallest value in real-time during ng-repeatiteration

In my HTML code, I am utilizing the ng-repeat function. When the user clicks on addBox(), a new input box is appended for adding new data:

<div class="col-md-6 col-md-offset-2">
  <h5 class="over-title">Variant</h5>
    <a class="btn btn-info" ng-click="addBox()" ng-hide="btnVarianthide">Add Variant</a>
</div>

This is the HTML structure:

<table>
  <tbody>
    <tr ng-repeat="row in product.variant.variantdetail">
      <td><input type="text" ng-model="row.variant_dtl_name" required></td>
      <td>
        <div class="input-group">
          <span class="input-group-addon">USD</span>
          <input type="number" ng-model="row.variant_dtl_price" required>
        </div>
      </td>
      <td>
        <a ng-click="delVariantDetail($index)">
          <i class="glyphicon glyphicon-trash"></i>
        </a>
      </td>
    </tr>
  </tbody>
</table>
<a class="btn btn-default" ng-click="addVariantDetail()">Add Variant Detail</a>

The controller functions are as follows:

$scope.addBox = function() {
  $scope.variantArray = [];
  $scope.product.variant = {
    variantname: '',
    variantdetail:[{
      "variant_dtl_name": '',
      "variant_dtl_price": ''
    }]
  }
  $scope.btnVarianthide = true;
  $scope.boxShow = true;
};

$scope.addVariantDetail = function() {
  $scope.product.variant.variantdetail.push({
    "variant_dtl_name": '',
    "variant_dtl_price": ''
  });
};

$scope.delVariantDetail = function($index) {
  $scope.product.variant.variantdetail.splice($index,1);

  if($scope.product.variant.variantdetail.length == 0) {
    $scope.btnVarianthide = false;
    $scope.boxShow = false;
    delete $scope.product.variant;
  }
};

I need to retrieve the value of row.variant_dtl_price from each newly added input box in order to track the minimum value for discount calculation. Can someone help me with this? Thanks!

Answer №1

To monitor changes in your array within the $scope, you can utilize the ng-change directive.

<input type="number" ng-model="row.variant_dtl_price" required ng-change="calcMin()">

Next, create a function in your controller that recalculates the minimum value whenever there is a change in detail price or when a new detail is added.

$scope.min = null;
$scope.calcMin = function(){
    var min = $scope.product.variant.variantdetail[0]["variant_dtl_price"];
    var allVariants = $scope.product.variant.variantdetail;
    for(var i=1;i<allVariants.length;i++){
        if(allVariants[i]["variant_dtl_price"]<min){
            min=allVariants[i]["variant_dtl_price"];
        }
    }
    $scope.min = min;
}

Check out this demo for a visual representation.

For further information:

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

Tips for seamlessly integrating an overlay into a different image

My current system is set up to overlay the image when you check the checkboxes. However, I'm facing an issue with positioning the image inside the computer screen so it's not right at the edge. Can anyone provide assistance with this? <html&g ...

What could be causing the Type Error in jsdom?

When attempting to parse a remote site using jsdom, I encountered an error when trying to use it with node-webkit.js: I received the following error: "Uncaught TypeError: A 'super' constructor call may only appear as the first statement of a f ...

Issue at hand: Unexpected error 500 encountered while sending AJAX request to PHP script through

UPDATE: Issue Resolved! I want to extend my gratitude to everyone who directed me to the error log files for assistance. The community here is truly incredible and I was able to get a resolution much quicker than anticipated. It's quite embarrassing, ...

Apply a border to the navbar when it hovers over a selected element

export const NavBar = () => { return <div className="navbar">this is navbar</div>; }; const Content = () => { return ( <div className="main"> <div className="background"> some content </div> ...

Refreshing and reloading within the same jQuery function

My PHP application involves the use of 2 PHP files. chart.php - This page includes a Google chart. <div id="chart_div" style="height:100%;width:100%"> </div> <script type="text/javascript"> google.charts.load('current', ...

Populate several input boxes with data derived from a single input field

I am facing an issue with three textboxes in my project. When I type something in the first textbox, the value is sent to state.jsp and displayed using out.println(firsttextboxvalue); on the response ID of the second textbox. However, I want to populate th ...

How can we alert users when data has been updated without the need for a page

The following code was authored by me: $('.actionButton').click(function(){ var buttonValue = $(this).val(); var userId = '<?php echo $_SESSION['id']; ?>'; console.log(userId); ...

Is there a way to load a URL within a DIV element using AJAX?

These two PHP files are set up to capture a user's input from a form and then display that text. Below you'll find the code for each file: file1.php: <form action="output.php" method="post"> Paste text document: <br> ...

Maximizing the Potential of Return Values in JavaScript

I have a JavaScript code that retrieves information and displays it in a div. It's functioning properly, but I want to dynamically change the div id based on the returned data. For example: function autoSubmit3() { $.post( 'updatetyp ...

Exploring the plane intersection within a 3D object using Three.js

I attempted to create an animation using Three.js to display the intersection plane on a 3D object with the following code snippet: import React, { useRef, useEffect, useState } from 'react'; import * as THREE from 'three'; export cons ...

Web Page Content Scrambling/Character Exchange

I've encountered a perplexing issue that seems to strike randomly, yet I've managed to replicate the problem on three different desktops. Oddly enough, some other desktops never experience this issue and I'm at a loss as to what could be cau ...

To trigger OnClick events in Next.js SSG, you will need to double click the element for it to run properly

There seems to be an issue where elements with an onClick event listener require a second click to run. It appears that the state is not updating on the initial click, causing this behavior. This problem may be related to using getStaticProps() for SSG on ...

Error Encountered in AngularJS: Request Unexpected (No Additional Requests Anticipated)

In my AngularJS project, I'm facing a challenge in writing unit tests to verify that executing a promise's then function changes the location.url. The function login within the AuthenticationService service is responsible for this behavior. Belo ...

Forcing a property binding update in Angular 2

Take a look at this particular component import {Component} from 'angular2/core' @Component({ selector: 'my-app', providers: [], template: ` <div> <h3>Input with two decimals</h3> <input type ...

deleting a class after a function has been executed

Just starting out with Angular and wondering if it's possible to make this change directly in the html: <td ng-class="{'lines-hover': !row.noSpread, 'line-selected': row.spreadSelected}"></td> I current ...

When the mouse drags across the empty space, the force graph continually jumps

I have some questions. I utilized a force graph and added zoom functionality to it. However, when I drag the mouse over the blank area, the force graph keeps jumping erratically. like this Is there a way to prevent the graph from jumping? Thank you. ( ...

Error: The "toString" property of an undefined variable cannot be read in uploadify

I'm having trouble with uploadify and trying to debug the issue. When attempting to use uploadify in Chrome, I encounter the following error: Uncaught TypeError: Cannot read property 'toString' of undefined Below is my html code: <li ...

Model updating with the addition of an item and triggering a secondary ng-repeat for refreshing

As I was working on the phone tutorial, I found myself pondering how to implement a specific use case. The browser renders a list of phones. When the user clicks on add phone for one of these phones, the function addItem is triggered and adds that phone ...

Utilizing a 2D array that has been downloaded previously and reusing it as a 2D array once more

I am working with a 2D array in JavaScript within a Google Chrome extension. Each index contains text with various characters. I have successfully converted this 2D array into a CSV file and provided code for downloading it: function Download(){ //https: ...

Using Jquery select2 to transfer and fetch information

Hey there, I've been experimenting with the jquery select2-plugin and I wanted to share the basic usage: Here's a simple example: <select style="width:300px" id="source"> <optgroup label="Alaskan/Hawaiian Time Zone"> < ...