Search code examples
javascriptangularjsangularjs-ng-repeatangularjs-filter

Advanced AngularJS custom filtering on ngRepeat objects


I want to achieve the following theoretical code:

VIEW.html

<li ng-repeat="player in players | filter:myCustomFilter(player)">{{player.name}}

CONTROLLER.js

// some theoretical conditional statement that return a boolean
$scope.otherCondition = true;


$scope.myCustomFilter = function(player) {
    return player.name.substring(0,1).match(/A/gi) && $scope.otherCondition;
}

So I want all of my players to be loaded into an Angular model, but I only want to render players into the DOM whose names start with the letter 'A'. When I try and do something like this, my console informs me that player is undefined. Do I need to write a custom filter in order to achieve this (via angular.module().filter())?


Solution

  • Here's a working fiddle: http://jsfiddle.net/orlenko/jV6DK/

    Html code (exactly as Karl Zilles suggested):

    <div ng-app>
        <div ng-controller="MyController">
            <h2>Names starting with "A":</h2>
            <ul>
                <li ng-repeat="player in players | filter:myCustomFilter">{{player.name}}</li>
            </ul>
            <h2>All Names:</h2>
            <ul>
                <li ng-repeat="player in players">{{player.name}}</li>
            </ul>
        </div>
    </div>
    

    Javascript:

    function MyController($scope) {
        $scope.players = [{
            name: 'Arthur'        
        }, {
            name: 'William'
        }, {
            name: 'Bertha'
        }, {
            name: 'Alice'
        }];
    
        $scope.otherCondition = true;
    
        $scope.myCustomFilter = function(player) {
            return player.name.substring(0,1).match(/A/gi) && $scope.otherCondition;
        }
    }
    

    Result