angularjs中的比较运算符函数

时间:2017-09-17 05:15:26

标签: jquery css wordpress

我是angularjs平台的新手,我面临解决我的雇主给出的小任务的问题。我希望有人可以帮助我。

我有一组员工表,我需要在ng-option中使用比较运算符,然后在数字字段中输入数字以获得结果。 (例如,如果用户选择大于ng-option并在文本字段中输入'50',结果应该从数据表中过滤大于50的年龄。任何人都可以帮忙!!

这是我试过的

$scope.operators = [
            {
                field: "gt"
                title: ">"
                }
                , {
                field: "lt"
                title: "<"
                }
                , {
                field: "et"
                title: "="
                }
             ];
        $scope.selected = $scope.operators[0];
        app.filter('priceGreaterThan', function () {
            return function (input, price) {
                var output = [];
                if (isNaN(price)) {
                    output = input;
                }
                else {
                    angular.forEach(input, function (item) {
                        if (item.redemptions > price) {
                            output.push(item)
                        }
                    });
                }
                return output;
            }
        });

1 个答案:

答案 0 :(得分:1)

您好,您可以使用过滤器完成所有三个操作!请参阅以下示例代码。

你的过滤器工作得很好,我添加了if else条件来执行不同的操作,还创建了一个用于显示输出的表,所以我没有将价格单独传递给过滤器,而是传递了一个对象({ {1}})然后在过滤器内使用以获取价格和操作员,请检查我的代码并告知我是否有任何问题。

&#13;
&#13;
{price: price, operator: selected.field}
&#13;
var app = angular.module('myApp', []);

app.controller('MyController', function MyController($scope) {
  $scope.data = [{
    name: 1,
    redemptions: 100
  }, {
    name: 1,
    redemptions: 150
  }, {
    name: 1,
    redemptions: 200
  }, {
    name: 1,
    redemptions: 50
  }, {
    name: 1,
    redemptions: 1
  }, {
    name: 1,
    redemptions: 10
  }]
  $scope.operators = [{
    field: "gt",
    title: ">"
  }, {
    field: "lt",
    title: "<"
  }, {
    field: "et",
    title: "="
  }];
  $scope.selected = $scope.operators[0];
});

app.filter('priceGreaterThan', function() {
  return function(input, params) {
    var output = [];
    if (isNaN(params.price)) {
      output = input;
    } else {
      angular.forEach(input, function(item) {
        if (params.operator === "gt") {
          if (item.redemptions > params.price) {
            output.push(item);
          }
        } else if (params.operator === "lt") {
          if (item.redemptions < params.price) {
            output.push(item);
          }
        } else {
          if (item.redemptions == params.price) {
            output.push(item);
          }
        }
      });
    }
    return output;
  }
});
&#13;
&#13;
&#13;

相关问题