gpt4 book ai didi

jquery - AngularJS中的比较运算符函数

转载 作者:行者123 更新时间:2023-12-01 08:41:45 26 4
gpt4 key购买 nike

我是 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;
}
});

最佳答案

您好,您可以使用过滤器来完成所有这三个操作!请引用下面的示例代码。

您的过滤器效果很好,我添加了 if else 条件来执行不同的操作,还创建了一个用于显示输出的表格,因此我不是将价格单独传递给过滤器,而是传递一个对象({price:price,operator:selected.field}),然后在过滤器内使用该对象来获取价格和运算符,请检查我的代码,如果有任何问题请告诉我.

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;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
<input type="text" ng-model="price">
<select name="operator" id="test" ng-model="selected" ng-options="x as x.title for x in operators"></select>
<table border="1">
<tr>
<th>Name</th>
<th>Redemptions</th>
</tr>
<tr ng-repeat="j in data | priceGreaterThan: {price: price, operator: selected.field}">
<td>{{j.name}}</td>
<td>{{j.redemptions}}</td>
</tr>
</table>
</div>

关于jquery - AngularJS中的比较运算符函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46260923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com