存储在 Angular 中连续求值的对象表达式

Storing object expressions that continuously evaluate in Angular

大家好

我 运行 今天在构建原型电子商务网站时遇到了一个意想不到的问题。具体来说,我有一个方法设置为接受用户输入并根据以下条件应用折扣:

1).代码是否正确(这在我的代码中由对象键表示)。

2).用户当前的总数是否满足某些最低标准(由 $scope.total 比较表示)。

这是我用来实现此目的的代码:

$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);
   };
 };
};

问题是我真的不喜欢在方法中定义这个庞大的对象。我最初尝试将它分配给 $scope 上的一个变量,但是我发现这只会设置一次值,即每当用户将商品添加到他们的购物车并因此增加 'total' 价格时,这不会反映在 $scope 变量中。

由于 $scope.total 在我的控制器加载时初始设置为 0,因此它将始终保持该值。

有没有更好的方法来处理这个问题?任何帮助将不胜感激!

我认为这是使用 Filters 的好案例。

代码

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

标记

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

Plunker

^ 已更新您的问题

标记

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

代码

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

^ 编辑

我现在注意到你的 var 代码,你可以像这样发送额外的参数

标记

<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>

并像这样接收它们

代码

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;
  }]);