1

I am having a little difficulty using a custom filter. I have searched and searched but cannot find anything relevant, but it should be a quick fix for someone with a bit of experience.

I am using ng-repeat to populate a list, this is from vm.posts.

The user that is logged in and viewing the posts is vm.user, and has a variable vm.user.postsWatched, which is an array of post ids.

I created a custom filter to check if the post has a 'watched' id and if so display it.

In my filter I am printing the contents of both variables and finding that I am not quite getting what I am trying to send in.

Index.html:

  <ul class="media-list">
          {{vm.user.postsWatched}}
          <li ng-repeat="post in vm.posts | watchedFilter:vm.posts:vm.user.postsWatched | limitTo:3" class="media">
            <div class="media-body">
              <h4 class="media-heading">{{post.title}}</h4>
              <p>{{post.date | date: 'short'}} | {{post.content}}</p>
            </div>
          </li>
        </ul>

On line two, the correct array of post Ids is displayed, so I know there is no issue there.

vm.posts and vm.user.postWatched are passed to watchedFilter as parameters, is there an issue so far??

watchedPost.filter.js:

(function () {
'use strict';

angular
    .module('app')
    .filter('watchedFilter', function () {  
           return function(inputs,ids) {
              console.log("ids:" + JSON.stringify(ids[0]) + JSON.stringify(ids[1]) + JSON.stringify(ids[2]));
              console.log("Input:" + JSON.stringify(inputs[0]) + JSON.stringify(inputs[1]) + JSON.stringify(inputs[2]));
             ...

           };
        });})();

Before I even begin filtering, the contents of the function parameter 'ids' does not equal vm.user.postsWatched, but rather contains the same info as 'inputs'. So I can tell it's getting a parameter alright, but seemingly not both, if someone could clarify it would really help me out.

If more is needed just ask, many thanks :D

1 Answer 1

1

In your HTML remove the first argument.

<li ng-repeat="post in vm.posts | watchedFilter:vm.user.postsWatched | limitTo:3" class="media">

When the AngularJS framework calls the filter function, it sets the first argument to the data being piped. The subsequent arguments are set from the arguments in the HTML.

Sign up to request clarification or add additional context in comments.

2 Comments

ok that's brilliant I'll try it out right away, many thanks :D
Thanks @georgeawg - this is perfect, it was pretty silly to assume I needed to pass a filter the objects I was already iterating, many thanks for your quick response

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.