1

I have a custom data type Message:

function Message(body, author, date) {
    this.body = body;
    this.author = author;
    this.date = date;
    this.stars = [];
}

Message.prototype.hasStars = function() {
    return this.stars.length !== 0;
};

I'm also doing a repeat on an array of these messages:

<li ng-repeat='message in messages | orderBy:"-stars.length"'>…</li>

How can I add a filter to it that calls message.hasStars()? I tried the following but none of them had effect:

message in messages | filter:message.hasStars() | orderBy:"-stars.length"
message in messages | filter:message:hasStars() | orderBy:"-stars.length"
message in messages | filter:message.hasStars | orderBy:"-stars.length"
message in messages | filter:message:hasStars | orderBy:"-stars.length"
4
  • You need a custom filter for that Commented Aug 29, 2013 at 18:30
  • 1
    @sza This is not true. See "Words Like Jared"'s answer. Commented Aug 29, 2013 at 19:28
  • @jessegavin That is nothing but a filter. You can create a filter using filter module or just a function. Commented Aug 29, 2013 at 19:31
  • 1
    It's a predicate function, but it's not registered through the dependency injector in angular as a 'filter'. Commented Aug 29, 2013 at 19:33

2 Answers 2

4

http://jsfiddle.net/DGKNN/

filter expects there to be an expression that evaluates to a predicate on the scope. That is a function that takes in an element as its parameter and returns whether or not the element should be included in the collection.

In your controller:

$scope.hasStars = function (message) {
    return message.hasStars();
};

In your view:

<li ng-repeat='message in messages | filter:hasStars | orderBy:"-stars.length"'>...</li>
Sign up to request clarification or add additional context in comments.

Comments

1

I'm a assuming some service called mySrv to load messages into your controller.

myapp.controller('myCtrlr',['$scope','mySrv',function($scope,mySrv){
    $scope.messages = mySrv.getMessages();
}]); // end myCtrlr

myapp.filter('hasStars',function(){
    return function(msg){
        return msg.stars.length > 0;
    };
});

In the template

<ul ng-controller="myCtrlr">
    <li ng-repeat="message in messages | hasStars | orderBy:"-stars.length">...</li>
</ul>

1 Comment

Did you mean to not put messages on the $scope?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.