I am making a Web App using angularjs. I have a list of posts that are fetched from the backend in the following structure:
[
{
post: {
postID: 1,
title: "sample title",
body: "so many paragraphs here",
post_date: "2018-12-26 02:21:35"
}
tags: [
{
tagTitle: "training"
},
{
tagTitle: "another tag"
}
]
}
]
I want to filter these posts according to the tag that I have clicked on. Say I have clicked on training, I want to display posts that have the training entry in their tags's array.
Since it's an angularjs Web App, the ui-sref is posts(filter: 'training') and the path (url) will be posts?filter=training.
I have created a filter with the following code:
function postsFilter() {
return function (collection, params) {
return collection.filter(function (item) {
var i, tagsArray = item.tags, len = tagsArray.length;
for (i = 0; i < len; ++i) {
return tagsArray[i].tagTitle === (
params.filter === "none" ? tagsArray[i].tagTitle :
params.filter;)
}
});
};
}
angular.module('app').filter('postsFilter', postsFilter);
In the controller, I have the following code;
function PostsController($filter) {
angular.extend(this, {
$onInit: () => {
this.filteredPosts = $filter('postsFilter')(this.posts, this.filter);
}
}
}
In the component I have the following code:
const posts = {
bindings: {
posts: '<',
filter: '<'
},
templateUrl: 'path/to/my/posts.html',
controller: 'postsController'
};
angular.module('app').component('posts', posts).config(
[
'$stateProvider', function ($stateProvider) {
$stateProvider.state (
'posts', {
url: '/posts?filter',
component: 'posts',
params: {
filter: {
value: 'none'
}
},
resolve: {
posts: ['PostsService', function (PostsService) {
return PostsService.getPostList();
}],
filter: ['$transition$', function ($transition$) {
return $transition$.params();
}]
}
}
);
}
]);
In the posts.html I then want display the filtered posts like:
<div ng-repeat='post in $ctrl.filteredPosts'>
{{post.post.title}}
</div>
With my current code, when I click on a link to filter the posts (say ui-sref='posts({filter: 'angularjs'})), the posts don't get filtered. The url changes but the posts still display all of them. By default, url to posts shows /posts?filter=none. When I click on a link to filter the posts (say the tag is angularjs), the url changes to /posts?filter=angularjs.
How should I make this correct?
OK, now it is working after putting those missing curly braces. The problem I now have is that, if a post has two or more tags, I can't filter it with the other tags, it only works with the first tag.
In this example, it will only be filtered with training, it doesn't get filtered with another tag.. In ideas to get this to work?