gpt4 book ai didi

javascript - Angular - 过滤嵌套对象

转载 作者:行者123 更新时间:2023-11-28 00:44:57 26 4
gpt4 key购买 nike

我有一个 JSON 对象数组,正在通过搜索进行过滤。在搜索中,我将搜索上的 ng-model 设置为 search.$,但它只搜索每个对象的顶部,但我需要to 搜索嵌套在对象内部的所有对象。在 Angular 中是否有一种简单的方法可以做到这一点?

最佳答案

可以使用自定义递归过滤器函数(有关文档,请参阅 https://docs.angularjs.org/api/ng/filter/filter ),以下示例说明了这一点:

angular.module('deepFilterTestApp', [])

.filter('deepFilter', function($filter) {
return function(text) {
return function (value) {
var searchTerm = text;
if (angular.isObject(value)) {
var found = false;
angular.forEach(value, function(v,k) {
found = found || $filter('deepFilter')(searchTerm)(v);
});
return found;

} else if (angular.isString(value)) {
if (value.indexOf(searchTerm) !== -1) {
return true;
} else {
return false;
}
}
};
};
})

.controller('DeepFilterTestController', function ($scope) {

$scope.myArray = [
{
property1: {
deepProperty1: "deeepppp 1!!"
},
property2: {
deepProperty2: "deeep 2!!"
}
},
{
property1: {
deepProperty1: "dooop 1!!"
},
property2: {
deepProperty2: {
evenDeeperProperty1: "deeepest 2!!"
}
}
}
];


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="deepFilterTestApp" ng-controller="DeepFilterTestController">

<p>"dooop": {{ myArray | filter : ('dooop'|deepFilter) }}</p>
<p>"deeep": {{ myArray | filter : ('deeep'|deepFilter) }}</p>
<p>"deeepppp": {{ myArray | filter : ('deeepppp'|deepFilter) }}</p>
<p>"deeepest": {{ myArray | filter : ('deeepest'|deepFilter) }}</p>

</div>

关于javascript - Angular - 过滤嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27516467/

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