Exploring the wonders of math in Angular with ng-repeat

Exploring the realm of mathematics within an angular expression, let's consider a scenario where a user can either have credit on the site or receive a percentage discount. Below is the code snippet in question:

<div ng-repeat="item in NewArrivals">
<div>{{item.NewPrice - userCredit | number:2}}</div>
<div>

The challenge at hand is to adjust the calculation based on whether the user is logged in or not. If the user is logged in, userCredit should be a set value. If not, userCredit should represent a 5% deduction from item.NewPrice.

These conditions are defined in the 'PageController.js' file:

if (TheUser == "notThere") {
    console.log('5% discount for the user')
    var userDiscount = 0.95;
} else {
    var userCredit = 300;
}

How can we achieve the subtraction of 5% from newPrice for each item in the ng-repeat loop when the user is logged in, without duplicating the ng-repeat structure?

Answer №1

Here is a method for effectively managing it

<div ng-repeat="item in NewArrivals">
  <div ng-if="userDiscount">{{item.NewPrice * userDiscount | number:2}}</div>
  <div ng-if="userCredit">{{item.NewPrice - userCredit | number:2}}</div>
<div>

Answer №2

In order to access the value in your template, you must include it in the $scope (or if you are using controller-as syntax, add it to the controller). Additionally, the syntax var userCredit = 5%; is not valid in javascript. You can achieve this by following the code below:


if (TheUser === "notThere") {
   $scope.userDiscount = 0.95;
} else {
   $scope.userDiscount = 1.0; // It's uncertain what value you want here.
}

Afterwards, insert this in the template:

<div ng-repeat="item in NewArrivals">
  <div>{{item.NewPrice * userDiscount | number:2}}</div>
<div>

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 canceling an http request in angularjs when the requesting controller has exited its scope

Developed a custom angularjs application with ng-view for loading four different modules using route provider. Each module makes HTTP requests as shown below: var requestManager = { "locations": {}, "employees": {}, "items": {}, "templates ...

Generate a graphical representation with react-d3

In an attempt to create a histogram using react-d3-components, I have the following code: import React, { Component } from 'react'; import * as d3 from 'd3'; import * as ReactD3 from 'react-d3-components'; import propTypes fr ...

Tips for concealing an input IP Address in React

Looking for suggestions on an IP Address mask input solution. The format might vary between 999.99.999.99 and 99.9.99.9, but react-input-mask does not support varying lengths. Any recommendations? ...

Inject a jQuery form submission using .html() into a div element

I am currently working on developing a basic forum where users can view listed topics and have the option to add new ones on-the-fly by clicking a link or image. How can I detect and handle the form submission event for the dynamically added form within an ...

Enable the execution of a function only once a specific period of time has elapsed

Here's the scenario I'm dealing with: In a fun group chat with my friends, I created a giphy bot that responds to /giphy [terms] messages by posting the top result for those terms. However, my friends started abusing it by spamming the chat. To ...

Regions for the MEAN stack

On our website, let's call it "www.xxxx.com," we need to develop a sub-portal dedicated to a specific company referred to as "www.xxxx.com/company1." This sub-portal should contain all the necessary controllers and views within an Area called "Company ...

Grabbing a specific section of a URL in AngularJS: Tips and Tricks

I have a URL that appears as: www.ccadmin/admin.jsp?id=Aetna834 Is there a way to extract the value Aetna834 from it? ...

What is the reason behind div elements shifting when hovering over a particular element?

Currently, I have floated all my div elements (icons) to the left and margin-lefted them to create space in between. I've displayed them inline as well. However, when I hover over one element (icon), the rest of the elements move. Can you please help ...

What could be causing the 404 error I'm receiving for this specific URL?

Can someone explain why I keep encountering a 404 error when I type \book into the URL bar? Below is the code I am currently using: var express = require('express'), app = express(), chalk = require('chalk'), debug = ...

Updating serialized $_POST array with new key/value pair using jQuery AJAX

Is there a way to insert additional values into a serialized $_POST array before sending an AJAX request using jQuery? Here's the situation: $('#ajax-preview').on('click', function(e) { e.preventDefault(); var formData = ...

Sharing controller methods in Angular.js is a key aspect of enhancing

In my current project, I originally used Knockout for the CMS functionality, but decided to switch to Angular because I preferred its features. One of the key sections in the CMS is dedicated to 'Users', featuring a table where headers can be cli ...

Issue with Vue parent component's inability to listen to event emitted by child component

Child component is triggering a custom event: <template> <div id="controls-container" class="controls-container"> <div class="control-button icon-zoom-in" @click="zoomHandler('+')"></div> <div class="control- ...

Add a fading transition feature to images that are loaded at a later time

I used a clever technique to create a blur effect by loading a small, lightweight image first. Once the main background image is loaded, it swaps out the 'data-src' with the actual image. However, I am facing an issue with the abrupt transition, ...

Adding a three-dimensional perspective to an HTML5 canvas without utilizing CSS3 or WebGL

Here is a canvas I am working with: http://jsbin.com/soserubafe Here is the JavaScript code associated with it: var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var w = canvas.width; var h = canvas.height; var cw=canvas. ...

What is the best way to explain the concept of type indexing in TypeScript using its own keys?

I'm still learning TypeScript, so please bear with me if my question sounds basic. Is there a way to specify the index for this type so that it utilizes its own keys rather than just being an object? export type TypeAbCreationModal = { [index: stri ...

How can I substitute specific words in a string with multiple words from an array?

I'm faced with a challenge where I need to replace asterisks (*) in a sentence with words from an array. Let's take an example: let sentence = 'My * is * years old.'; let words = ['dog', 3]; //expected result => My dog is ...

Dragging a Google Maps marker causes a border to appear around a nearby marker

Recently, I added a main draggable marker to the map. However, an unusual issue arises when dragging this marker - a blue outline appears around one of the existing markers on the map. This behavior is puzzling as it seems to be triggered by a click event ...

Issue: No default template engine specified and no file extension provided. (Using Express framework)

While I came across numerous questions with a similar title, they only provided me with partial help and did not completely resolve the error that plagued me. Just to provide some context, I had created a file named listing.js as a tool for running node c ...

Enhance the speed of webview on Android devices

I have been working on an application that utilizes a webview to load both HTML and JavaScript files. Unfortunately, I have noticed a significant decrease in performance when displaying the content. Despite trying various solutions such as: webVi ...

Troubleshooting: Issue with auto height functionality in Angular's ui-grid

Utilizing angular's ui-grid to display records, I have a scenario where one product has 7 entries and another product has 200 entries. By default, the grid is set to display a maximum of 20 rows when there are more than 20 records. If there are less t ...