Combining a user-entered number with a fixed variable in Angular.js

Have another question about Angular:

I'm trying to create a functionality where the value entered in the #quantity input is multiplied by the item's price stored in the controller.

For instance, if the price is 99.00 and the user enters a quantity of 2, the result of 99 * 2 should be displayed in the .total div.

How can I achieve this?

Here is the relevant HTML code snippet:

<input type="number" min="0" max="10" id="quantity" name="store-quantity" value='1'/>
<div class="total">
    <!-- Total will be displayed here -->
</div>

A glimpse of my store.controller.js file:

angular.module('angularStoreApp')
    .controller('StoreCtrl', function ($scope, $http) {
        var item = [
            {
                name: 'Almond Toe Court Shoes, Patent Black',
                price: 99.00,
                category: 'Womens Footware',
                stock: 5,
                canPurchase: true,
                images: [
                    "assets/images/yeoman.png",
                    "http://billypurvis.co.uk/wp-content/uploads/2015/06/ACTA.png"
                ]
            },

Answer №1

I decided to create a live example showcasing the code provided in the initial question, enhanced with some modifications.

Let's take a closer look at the key snippet of the code:

<div ng-repeat="item in items" ng-show="item.available " class="item-wrapper">
  <div class="full product-details">
    <h1>{{item.name | limitTo: 20}}...</h1>
    <h2 class="full">{{item.price | currency}}</h2>
    <div ng-hide="{{item.stock <= 0}}">
      <input class="voucher-input" placeholder="Enter Voucher Code" />

      <input type="number" ng-model="quantity" max="{{item.stock}}"/>
      <input type="submit" value="Purchase Now" />
      <div class="final-price">
        Total: {{ item.price * quantity | currency }}
      </div>
    </div>
  </div>
</div>

To begin, I included ng-model="quantity" within the input field, establishing quantity as a reusable variable. As each iteration of ng-repeat generates a distinct scope for that section, a unique quantity will be associated with every item in the loop.

Furthermore, I integrated max="{{item.stock}}" into the input element, illustrating the capability to bind an object property to a standard HTML component. If a user inputs a quantity exceeding item.stock, the system sets quantity to NaN.

Lastly, I incorporated the essential calculation

Total:{{ item.price * quantity | currency }}
. In this instance, I applied the currency filter to ensure that if quantity is either 0 or NaN, the output will display as empty instead of displaying NaN.

Answer №2

Give this code a try:

<div ng-app="customStoreApp" ng-controller="ShopCtrl as shopCtrl">
    <input type="number"  min="0" max="10" id="amount" name="shop-quantity" value='1' ng-model="amount"/>
    <div class="final-price">
        {{ shopCtrl.products[0].cost * amount }}
    </div>
</div>

Also, add the following:

angular.module('customStoreApp', [])
    .controller('ShopCtrl', function ($scope, $http) {
        $scope.amount = 0;
        this.products = [
            {
                name:  'Stylish Sunglasses, Polarized Black',
                cost: 59.99,
                category: 'Accessories',
                inventory: 8,
                inStock: true,
                pictures: [
                    "images/sunglasses.png",
                    "images/bracelet.png"
                ]
           }
       ];
  })

Remember to substitute the item's Id with your own (in this scenario, it's 0)

Take a look at this fiddle: https://jsfiddle.net/rx9qfdyz/

Be careful! Entering a number above 10 will lead to a null result.

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 mask overlay that covers the entire screen while excluding a specific sibling div

My goal is to create a div that acts as a mask covering the entire window. It should have an opacity of 0.5 and a background color of lightgray. However, there is one particular div on the screen that I do not want to be affected by the mask. I attempted t ...

Specifying the data type of the input being passed into a .css() function within a jQuery ID selector

Currently, I am facing an issue where I need to position an element below a fixed toolbar. The amount of top-padding required for this positioning varies based on the viewport width. To address this, I have created a formula that calculates the percentage ...

Do you need to have knowledge in reactjs in order to master react-native?

As I embark on the journey of learning how to build apps using react-native, a burning question arises in my mind: should I first learn react-js before diving into react native? Any guidance or advice would be greatly appreciated. Thank you. ...

What is the purpose of the 'onClassExtended' function in Extjs 6 for class definition?

Ext.define('Algorithm.data.Simulated', { needs: [ //.... ], onClassExtended: function(obj, info) { // .... } }) I came across this code snippet but couldn't locate any official documentation for it on Sencha ...

Is it possible to apply withStyles to the output of a function?

Currently, I am attempting to add extra styling to the output of a function that returns one of two components based on specific props. Here is an example: import React from 'react' import { withStyles } from '@material-ui/core/styles' ...

Node.js and Express make it easy to provide XLS download functionality

I have successfully utilized the code snippet below to generate an excel file in node.js. My intention is for this generated file to be downloadable automatically when a user clicks on a designated download button. var fs = require('fs'); var w ...

Error encountered in ASP.NET MVC when using AngularJS due to an unknown provider

I have been experimenting with angular Chart and angular Select. The Chart is working fine, but when I added a controller for the select control, an error occurred: Unknown provider: $$asyncCallbackProvider <- $$asyncCallback <- $animate <- $compi ...

The page continues to refresh even after the fetch() method is called and the promise is resolved, despite setting e.preventDefault()

Greetings! I am currently in the process of creating a basic API using ytdl and express. Specifically, the route I am focusing on is responsible for downloading a file. app.post('/audio', (req, res) => { console.log(`Initiating audio down ...

Authentication using tokens - JSON Web Tokens

While working with jsonwebtoken in Node, we generate a unique token for each user and return it to them. But when the user sends this token in the authentication header (Authentication: <token>), how does jwt differentiate between tokens from diffe ...

What could be causing the issue of Vuejs 3.3 defineModel consistently returning undefined?

I am currently working with Nuxt version 3.5.1 and Vuejs version 3.3, however, I am encountering an issue where the defineModel macro always returns undefined. I am unsure why this is happening? <template> <input v-model="count"& ...

Two events in an arrow-guided grid including a text box (jQuery)

I have successfully implemented an editable table using jQuery where users can click on a cell to input text. The goal now is to enable the use of ARROW keys for quick navigation within the table. Below is my current code: $( function () { $( "td" ). ...

Incorporating a new text tag

Is there a way to add a text label for every circle that can be rotated and have its color changed? I'm looking for a solution that doesn't involve JSON data, but instead retrieves the necessary information from somewhere else. var w = 3 ...

Manipulating DOM elements using JavaScript Vanilla with the Jquery <<S.fn.init [selector]>> framework

I have a project where I need to switch the logic written in jQuery to vanilla JavaScript. Here is an overview of my code: I am using the keydown event on an input element to trigger a function that searches an API based on the input value. var selectedU ...

What is the method for retrieving the hashed classname set by CSS Modules within a functional react component?

I am facing an issue with targeting a class named "nav" using querySelector because CSS modules hash the class name, turning it into something like nav-xyzxyz. Making it more complex, I have to verify if a class exists on an element with the class "nav", ...

Extracting information from this array using JavaScript

After struggling for a day, I finally managed to get some output from PHP instead of just the word "array". What a relief! (check out this link for the solution) Basically, this is the data returned from an XMLHTTP request to PHP, handled through a JS ca ...

Display the device model using Google Cloud Monitoring API

I've been utilizing a Node.js library to fetch metrics from my Google Cloud Compute Engine instances. You can find the library here. When creating a time series, the resulting data looks like this: { "points": [...], "metric": { "lab ...

How to create a gelatin-like effect on a rectangle using HTML5 canvas

Currently, I'm working on a platformer game project in JavaScript. The concept involves players as rectangles jumping on and off platforms. While the basic functionality is set up, I'm now aiming to incorporate a unique 'gelatine effect&apos ...

What is the reason that the name property does not display anything in the Edge browser after compression?

Currently, I'm using a module that utilizes various functions like Not, And, type, and typeIs to construct a query string based on the content type it is searching for. However, there seems to be an issue with one of these functions, particularly the ...

Using the 'type' field as a parameter in a Vue2 component object

I need help with passing an object into my component. Here is a snippet of the object's properties: { title: "myTitle", type: "myType" } However, when I define the prop in my component like this, I get a Vue runtime warning st ...

Textillate JS-JQuery animations are never the go-to choice (they all look alike)

I have been experimenting with the textillate.js library in order to incorporate animated text effects into my project. Here is a snippet of my HTML page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8& ...