AngularJS multiple select dropdown with dynamic quantity selection

I am currently utilizing AngularJS instead of Angular and I am looking to implement a corresponding textbox next to the dynamic select box.

Below is my code for dynamically adding select boxes:

HTML

<div ng-controller='MyController'>
    <div ng-repeat="addon in product_addons track by $index">
        <select    
            ng-model="addon.id" 
            options="products"
            ng-options="product.id as product.name for product in products"
            ng-disabled="product_addons.length > 1 && product_addons.length > $index + 1">
        </select>
        <input type="number" name="quantity">
        <button type="button" ng-click="addAddons($index)">-</button>
    </div>
    <button type="button" ng-click="removeAddon()">Add Product to Addon</button>
</div>

AngularJS

var app = angular.module('myApp', []);
app.controller('MyController', ['$scope', MyController]);    

function MyController($scope) {

    $scope.products = [
        {id: 1, name: 'prod1', price: 100}, 
        {id: 2, name: 'prod2', price: 100},
        {id: 3, name: 'prod3', price: 100}
    ];  

    $scope.product_addons = [{}];
    
    $scope.addAddons = function(){  
        $scope.product_addons.push({});
    }
    
    $scope.removeAddon = function(index){
        $scope.product_addons.splice(index,1);
    }
}

My goal is to include dynamic quantity input fields for each added dynamic select box

Answer №1

Understanding your goal can be a bit challenging, but I'll do my best to help.

It seems like you require a function that calculates the sum of values within your array of objects. So, each time you add an item, it gets pushed into the product_addons array, correct?

However, it appears that there may be an issue with how you are adding items to your array.

$scope.sumOfSelections = 0;

// Here is a predefined list of products
$scope.products = [
    {id: 1, name: 'prod1', price: 100}, 
    {id: 2, name: 'prod2', price: 100},
    {id: 3, name: 'prod3', price: 100}
];

$scope.product_addons = []; // Start with an empty array

// Function to add items from product list based on selected ID
$scope.addAddons = function(selectedId){
   $scope.product_addons.push($scope.products.find(element => element.id == selectedId););
   sumSelections(); // Invoke this after every operation that modifies the product_addons
}

// No need for this function to be exposed on $scope
function sumSelections() {
    $scope.sumOfSelections = $scope.product_addons.reduce((a, b) => a.price + b.price);
}

In your HTML, you can refer to {{sumOfSelections}} and observe it updating whenever you add a product to the $scope.product_addons array.

You will also need to develop a method to remove an add-on, which can follow similar principles for removing items from the same array.

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

Developing a concealed Repeater element that is retained in the source code for utilization in JavaScript tasks

I am currently working on a setup with two repeaters: one that is displayed when the page first loads, and another that I want to keep hidden until a link called "Add Stuff" is clicked. My goal is to use JavaScript to make this second repeater visible upon ...

Issues arising post transitioning to 14.0.0 from 13.0.0 version of ngx-masonry library leading to failed tests

Following the update to the latest stable version of the library ngx-masonry 14.0.0, our tests started failing. The release was just yesterday (24.10.2022) and you can find the changelog here: https://github.com/wynfred/ngx-masonry/blob/master/CHANGELOG.md ...

Can you provide an example of JSON for a MultiStep Form that includes a variety of control types for viewing

Could someone please provide me with JSON examples of multi-step forms that include various types of controls such as radio buttons, checkboxes, dropdown menus, and calendars? I am in need of JSON for both the view and edit forms. Your help would be grea ...

Guide to setting up a default route that precedes all other routes in Express.js routing

I'm struggling to articulate this question correctly, so please be patient with me. Currently, I have a few routes set up: localhost:3000/index localhost:3000/home localhost:3000/login localhost:3000/forgot However, I would like to add a client n ...

Exploring the contrasts in values within the ng-repeat directive of AngularJS

I am currently working with a JSON object that contains information about various clients, including the payments made over different date ranges within each month. My goal is to loop through this list of customers and display a table for each customer, hi ...

I keep encountering the error message "$firebase is not defined" while working on my reddit clone project on thinke

When I check my console, I see the following error: Error: $firebase has been removed. You may instantiate $firebaseArray and $firebaseObject directly now. This is my post.js service file: app.factory('Post', function($firebase, FIREBASE_URL){ ...

Get a URL from the JSON data returned by the Wikipedia API

How can I retrieve the image URL from a JSON response and store it in a variable? I found helpful information on the MediaWiki API help page Following this example to extract image information from a page: https://commons.wikimedia.org/w/api.php?action= ...

Substitute all instances of null bytes

I need to remove null bytes from a string. However, after replacing the null bytes \u0000 in the string let data = {"tet":HelloWorld.\u0000\u0000\u0000\u0000"} let test = JSON.parse(data).tet.replace("\u0000", ""); I always ...

Eliminate duplicated partial objects within a nested array of objects in TypeScript/JavaScript

I'm dealing with a nested array of objects structured like this: const nestedArray = [ [{ id: 1 }, { id: 2 }, { id: 3 }], [{ id: 1 }, { id: 2 }], [{ id: 4 }, { id: 5 }, { id: 6 }], ] In the case where objects with id 1 and 2 are already grou ...

The mongoose library requires JSON input, yet it is unable to generate a dynamic JSON object from a Node

This question delves more into javascript and JSON concepts rather than focusing on the mongoose library. When working with Mongoose, conditions are expected to be in JSON format, like so: { $or: [ { "doc_no" : /first/i }, { "doc_type" : /second/i } ] ...

The Canvas Clear function is malfunctioning; the items in the array are not being deleted

Even after being deleted from the array, the squares are still drawn. Shouldn't they disappear when removed from the Array? Does the array not update within the go function? Javascript: var canvas; var ctx; $(document).ready(function(){ $("#t ...

Utilizing Protractor to wait for the loading of elements, pages, or Angular functionality

Recently, I have been facing an issue with my code: browser.waitForAngular(); const EC = protractor.ExpectedConditions browser.wait(EC.visibilityOf(element), 10000); Despite trying to adjust the timeout duration to 10/20/30 seconds, I keep encountering a ...

Angularfire not updating $scope value

I've encountered an issue with my code. The $scope value doesn't update after using $createUserWithEmailAndPassword. However, when I use alert($scope.message), the alert appears. What am I doing wrong? I have all the latest files from firebase a ...

Encountering the error message "Uncaught TypeError: $.ajax is undefined"

Recently, I encountered an issue with my form that utilizes ajax to send user information to a php file. The form is embedded within a bootstrap modal and was functioning perfectly until I attempted to add an extra field for enhanced functionality. However ...

Iterating Through Multiple Dimensions

I am facing a challenge with creating rules from three arrays that I have. The task is to generate every possible combination of entries from each array, but I am struggling with the logic required to write a function for this purpose. For example: var ar ...

The AngularJS price slider may exceed its range if the ng-model is null or below the minimum value

I currently have an rz-slider featured on my webpage that is utilized for gathering the price of a product from the user. In addition to the slider, there are two input fields present which are designated for storing the minimum and maximum values. The ng- ...

Switching templates in AngularJS

We have a unique challenge from our client who wants a responsive website, but desires to make significant content changes that may push the limits of bootstrap. Although bootstrap allows for showing/hiding blocks and adjusting their positions with offset ...

I noticed that when I include the www in the URL, I am unable to retrieve the API results. However, when I exclude the

Whenever I try to access my website through www.mywebsite.in, it fails to display my data. However, if I visit the site without the www prefix, everything works fine and I can retrieve data from the database. I'm currently utilizing APIs for both get ...

Should I use one or two containers for my Dockerized Angular app?

Understanding how an Angular app works in Docker can be challenging. Angular requires a web server like nginx to run, as well as nodejs to access the backend. Should these be separated into two containers, or is there another way to handle this? Currently ...

Getting attribute values from custom tags in AngularJS is a common task that can be

I am new to AngularJS and I'm having trouble with my code. I am attempting to retrieve the attribute value of post-id from my index.html file and display it in the console from my controller. Here is a snippet from my index.html: <post-creator po ...