Advanced AngularJS custom filtering on ngRepeat objects
Solution 1
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;
}
}
Solution 2
You don't need to pass player to the filter
<li ng-repeat="player in players | filter:myCustomFilter">{{player.name}}
Should work
acconrad
I lead some web front end teams for Facebook dot com. I also run the GetToKnow Slack app to help you learn about your teammates and PeerGym for finding gyms in your local community. Need some technical expertise? Check out my boutique consulting firm.
Updated on June 25, 2022Comments
-
acconrad almost 2 years
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 (viaangular.module().filter()
)?