Alzor Alzor - 1 year ago 81
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:

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

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 -->

The getFilteredArticles method looks like this

$scope.getFilteredArticles = function (categoryId) {

var posts = $scope.posts;

posts.forEach( (object) => {
if ( object[Categories.Id] === categoryId ) {


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

"Title":"Test Title",
"Name":"Category 1",
"Name":"Category 2",

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?

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

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download