gpt4 book ai didi

javascript - 如何使用 Angular 过滤器过滤json

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:40:57 24 4
gpt4 key购买 nike

嘿,我对 Angular 过滤器没什么问题。我从 wordpress 导入帖子,我真的很想按标签过滤它们,比如,现在只显示标签 = ENG 的帖子,或者只显示标签 = GER 的帖子。这就是我的 html 的样子

    <div ng-controller="ThreeMainPosts">
<div ng-repeat="threePost in threePosts | filter : {data.data.posts[0].tags[0].slug = 'ENG'} ">
<div three-post="threePost">
<h1>CONTENT</h1></div>
</div>
</div>

Controller

myModule.controller('ThreeMainPosts', function($scope, $location, WordPressNewsService) {
var postsPerPage = 3;
var orderBy = 0;
WordPressNewsService.getPosts(postsPerPage, orderBy).then(function(data) {
$scope.threePosts = data.data.posts;
});

});和 json

    { id: 312, type: "post", slug: "la-bamba-3", url: "sada2", … }
attachments:[]
author:{ id: 1, slug: "ds", name: "hnews", first_name: "", last_name: "", … }
categories:[{ id: 6, slug: "ludzie", title: "Ludzie", description: "", parent: 0, post_count: 2 }]
tags: [{ id: 32, slug: "en", title: "EN", description: "EN", post_count: 1 }]
url:"http://xxx0.co,/?p=312"
previous_url:"http://hirsch-news.iterative.pl/?p=306"
status:"ok"

我尝试在 Controller 中制作过滤器,但我只能对单个元素执行此操作,例如:

if(data.data.posts[0].tags[0].slug == "ENG"){
$scope.threePosts = data.data.posts;
}

有什么想法吗?祝你有美好的一天! :)

最佳答案

制作了一个快速过滤器,可以根据您的需要进行更改。希望能帮助到你。 Angular $filter Docs

这是一个 Codepen使用 Angular 内置的 $filter。

myModule
.controller('ThreeMainPosts', function($scope, $location, WordPressNewsService, $filter) {
var postsPerPage = 3;
var orderBy = 0;
var tagToSortBy = 'EN'
WordPressNewsService.getPosts(postsPerPage, orderBy).then(function(data) {
$scope.threePosts = $filter('postFilter')(data.data.posts, tagToSortBy);
});
})
.filter('postFilter', function() {
return function(post, tag) {
if (post.tags.slug === tag) {
return post;
}
};
});

如果你想在模板中这样做,它会像这样。

<div ng-controller="ThreeMainPosts">
<div ng-repeat="post in threePosts | postFilter : 'ENG' ">
<div three-post="threePost">
<h1>CONTENT</h1>
</div>
</div>
</div>

关于javascript - 如何使用 Angular 过滤器过滤json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43258659/

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