Alzor Alzor - 1 month ago 12
AngularJS Question

Push object from one array to another based on parameter

So I have a list of news articles, and I need them to be filtered but server side not client side.

The way I'm filtering is by having a dropdown list that users click on to filter the articles like so:

<ul>
<li ng-repeat="category in categories">
<span href="" ng-click="getFilteredArticles(category.id)">{{category.title}}</span>
</li>
</ul>


and the articles are populated via an ng-repeat like so

<ul infinite-scroll="addPosts()" infinite-scroll-distance="0" infinite-scroll-disabled="stopScrolling" class="c-news">
<li ng-repeat="post in posts" class="c-news__item" ng-click="selectPost(post)">
<!-- Omitted some code for the sake of brevity -->
</li>
</ul>


The getFilteredArticles method looks like this

$scope.getFilteredArticles = function (categoryId) {

var posts = $scope.posts;

posts.forEach( (object) => {
if ( object[Categories.Id] === categoryId ) {
$scope.filteredArticles.push(object);
}
});

console.log($scope.filteredArticles);
}


A typical JSON object that I'm pulling through looks like this

{
"Title":"Test Title",
"Summary":"",
"PublishedDate":"2016-10-17T09:42:00",
"Author":{
"Id":"480586a5-2169-e611-9426-00155d502902",
"FirstName":"TestFirst",
"LastName":"TestSecond",
"Email":"test@test.com"
},
"Id":99,
"StatusName":"Published",
"Status":2,
"Categories":[
{
"Id":1,
"Name":"Category 1",
"ArticleCount":31,
"UnpublishedArticleCount":1
},
{
"Id":2,
"Name":"Category 2",
"ArticleCount":19,
"UnpublishedArticleCount":0
}
],
"AttachmentCount":0,
"FilesAwaitingCheckIn":0
}


What I'd like to happen is when the user clicks one of the filter choices, for the list to then filter to the clicked choice. I've got this far but then I'm getting a ReferenceError: Categories is not defined.

I based my getFilteredArticles() code from another Stack question which can be found here.

I'm aware of being able to just filter the ng-repeat however my manager does not want to go that route and would rather filter server side due to the amount of posts that we may have.

Any ideas?

EDIT
Here's what's inside $scope.posts array

Answer

As Categories is an array you need to loop through that array to get Id's

Your loop should be similar to this

$scope.getFilteredArticles = function (categoryId) {

        for(var i=0;i<$scope.posts.length;i++)
        {
            for(var j=0;j<$scope.posts[i]["Categories"].length;j++)
          {
            if($scope.posts[i]["Categories"][j]["Id"] == categoryId)
                $scope.filteredArticles.push($scope.posts[i])
          }
        }
        console.log(JSON.stringify($scope.filteredArticles));
    };
Comments