Saving dynamic object expressions that are constantly re-evaluated within Angular

Hello Everyone

During the development of a prototype e-commerce website, I encountered an unexpected issue today. Specifically, the challenge lies in a method designed to take user input and apply discounts based on two criteria:

1). Validation of a correct code (represented by object keys).

2). Meeting specific total conditions for the user's order (based on $scope.total comparisons).

Below is the current code implementation:

$scope.processDiscount = function(code) {
 var discountInfo = {
   'FIVE': {
     condition: true,
     discount: 5
   },
   'TEN': {
     condition: $scope.total > 50,
     discount: 10
   },
   'FIFTEEN': {
     condition: $scope.total > 75 && $scope.reviewCartCategories('Men\'s Footwear', 'Women\'s Footwear'),
     discount: 15
   }
 };
 for (var key in discountInfo) {
   if (code === key && discountInfo[key].condition) {
     $scope.applyDiscount(discountInfo, key);
   };
 };
};

The main concern is the large object defined within the method. Initially, I tried assigning it to a variable on the $scope, but faced the issue of it being set once and not updating with changes in the user's cart. This is because $scope.total is initially set to 0 when the controller loads, making it static.

I am seeking advice on a more efficient way to handle this situation. Any suggestions or assistance would be greatly appreciated!

Answer №1

I believe this is a great example to showcase the use of Filters.

Sample Code

angular.module('App', [])
  .filter('discount', function() {
    return function(input) {
      return input * 0.5;
    };
  })
  .controller('MyCtrl', ['$scope', function($scope) {
    $scope.total = 0;
  }]);

HTML Markup

<body ng-app="App" ng-controller="MyCtrl">
    <input type="number" ng-model="total"/>
    {{ total | discount }}
</body>

Plunker

^ Check out the Updated Question

More Markup

<body ng-app="App" ng-controller="MyCtrl">
    <input type="number" ng-model="total"/>
    discount = {{ total | discount }}
    total with discount = {{ total - (total |discount) }}
</body>

Updated Code

angular.module('App', [])
  .filter('discount', function() {
    return function(input) {
      switch(true){
        case (input > 50):
          return input * 0.1;
          break;
        case (input > 75):
          return input * 0.15;
          break;
        default:
          return input * 0.05;
          break;
      }
      return 0;
    };
  })
  .controller('MyCtrl', ['$scope', function($scope) {
    $scope.total = 0;
  }]);

Plunker

^ Edit

Just noticed that you can pass an additional parameter like this

More HTML Markup

<body ng-app="App" ng-controller="MyCtrl">
    <input type="number" ng-model="total"/>
    discount = {{ total | discount:'FIVE'}}
    total with discount = {{ total - (total|discount:'FIVE') }}
</body>

You can then receive and utilize these parameters in your code as shown below

CODE Example

angular.module('App', [])
  .filter('discount', function() {
    return function(input, code) {
      switch(true){
        case (code == 'FIVE'):
          return input * 0.05;
          break;
        case (input > 50 && code == 'TEN'):
          return input * 0.1;
          break;
        case (input > 75 && code == 'FIFTEEN'):
          return input * 0.15;
          break;
        default:
          return 0;
          break;
      }
      return 0;
    };
  })
  .controller('MyCtrl', ['$scope', function($scope) {
    $scope.total = 0;
  }]);

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

The function service.foo is not recognized in Angular

My service function is not being recognized by my component import { Injectable } from '@angular/core'; import { ToastController } from '@ionic/angular'; @Injectable({ providedIn: 'root' }) export class LocationService { ...

Is there a way to incorporate a JavaScript variable as the value for CSS width?

I created a scholarship donation progress bar that dynamically adjusts its width based on the amount donated. While I used CSS to handle the basic functionality, I am now trying to implement JavaScript for more advanced features. My goal is to calculate ...

show logged-in users on the screen

Can someone please assist me in updating my controller to change the username when the user is logged in? I am currently experiencing an issue where even after updating the user, the username field remains empty. Any help in resolving this would be greatly ...

Function exported as default in Typescript

My current version of TypeScript is 1.6.2 and we compile it to ECMA 5. I am a beginner in TypeScript, so please bear with me. These are the imported library typings. The contents of redux-thunk.d.ts: declare module "redux-thunk" { import { Middle ...

Subscription date is activated when a different part of the state changes in ngrx

Within my state, I have properties named start and end which store dates. Whenever any other part of the state is modified, the subscription for these start and end dates is triggered. Here is the subscription implementation: this.subs.sink = this.store ...

Retrieving the image source from the image element by utilizing $(this).find("");

Currently facing a challenge in retrieving the image source (e.g., ./imgs/image.jpg) from an image element. Managed to make some progress by using the following code: var image = document.getElementById("home-our-doughnuts-box-image").getAttribute("src" ...

I am struggling to retrieve information from HTML elements using the GET method in Node.js and MongoDB

Code Troubleshooting var userID = req.userid; var pwd = req.pwd; console.log("userid = " + userID + "pass = " + pwd); The console is displaying undefined values instead of the input data. I have a problem with fetching data from an HT ...

Displaying data on the user interface in Angular by populating it with information from the form inputs

I am working on a project where I need to display data on the screen based on user input received via radio buttons, and apply specific conditions. Additionally, I require assistance in retrieving the id of an object when the name attribute is chosen from ...

Building a React component to display JSON data in a tabular format

I am trying to create something similar to the layout in the following link: Table example Imagine I have two arrays: names: ["Prisma 2 Case", "PP-Bizon", ...] imgs: ["img1.png", "img2.png", ...] One array contain ...

Troubleshooting: Issues with AngularJS Data Binding in HTML Tables

I have been working on code from an online tutorial but unfortunately, it is not functioning properly. I have checked the script, app, and controller but still cannot identify the issue. Any assistance would be greatly appreciated! ...

Customizing CoreUI column names in Vue

I am working with an array of item objects for a table. For example: [{ name: 'Sam', age: 24 }] Instead of using the default column names like age, I want to set custom field names. For instance, I want to display the column as Id instead of age ...

Tips on updating the $authProvider.loginUrl for Satellizer from an Angular controller

Consider this hypothetical situation: A user attempts to access a /settings page without being logged in. The Settings controller detects based on $auth.isAuthenticated() != true that the user is not logged in, and directs them to the /login page. The us ...

Display the active item in ng-repeat using conditional ui-view

Here is the situation: I'm working with a list of items that are displayed using ng-repeat. Each item has its own template. When a user clicks on an item, that particular item is marked as "active" and gets a different template compared to the rest ...

React - Component not updating after Axios call in separate file

Recently I decided to delve into React while working on some R&D projects. One of my goals was to build an application from scratch as a way to learn and practice with the framework. As I started working on my project, I encountered a rather perplexin ...

Static variable storing instances of objects

I am faced with the following scenario: function Configuration() { } Configuration.users = { 'user1': new User() } The users variable is a static member of Configuration and I am attempting to have it store an instance of a User object. Howev ...

JSHow to dynamically access child elements in objects

I am facing a challenge in dynamically accessing a JSObject item: jsonElement = { name:"name", subElement { subElementName: "nameSubElement", } } Currently, I have the element as: //level = "name" jsonElement[level] -> it works //lev ...

Encountering a response code of 401 results in the exclusion of certain code

I'm currently developing an application using Ionic v1, Express, MongoDB, and Node.js. In my code for checking user authentication, I have the following snippet: checkAuthentication: function(token) { console.log(token); retur ...

The checkbox labeled "Shipping Same as Billing" is not functioning correctly. I have included my JavaScript code below, can someone please help me identify what I am overlooking? (Only JavaScript code is provided; HTML is

I'm having trouble transferring data from a 'shipping' address to the 'billing' address section. I've included all my code, but nothing seems to copy over when the check box useShip is selected. All the HTML code is provided f ...

Delete the final character from the value stored in the map

After retrieving data from the backend, I receive: {"Item":{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}} Utilizing Object.Keys, I filter ...

Guide to automatically logging into an AngularJS application using a specific URL

Is there a way to enable auto login using angularjs 1.x? I need the user to be automatically redirected to the home page when they click on a URL sent via email. The URL will contain an email and encrypted password: http://localhost:8080/login/[email ...