How to predicate filter, instead of using 2 ng-ifs?

时间:2015-07-28 23:25:58

标签: javascript angularjs angular-filters angular-ng-if

.teams(ng-repeat='team in service.teams' ng-class="{'last':$last}")
          .row
            .team.roster(ng-click='showPlayers = !showPlayers')
              .col-xs-7.col-sm-4.col-md-4.mainRoster-col
                .team-name
                  {{team.name}}

      //shows the player rating for the highest rated player

      .roster(ng-repeat="player in team.playerProfiles | orderBy: '-pRating' | limitTo:1" ng-if="!team.selected")
        .row
          .col-xs-1.col-sm-1.col-md-1.rosterCheck-col
          .col-xs-7.col-sm-7.col-md-7
            %table
               %tr
                 %td
                  .p_rating
                    {{player.pRating | percentage}}


       //shows a selected player, instead of showing the default player with highest rating

      .roster(ng-repeat="player in team.playerProfiles" ng-if="team.selected && team.selected.playerId == player.id")
        .row
          .col-xs-1.col-sm-1.col-md-1.rosterCheck-col
          .col-xs-7.col-sm-7.col-md-7
            %table
              %tr
                %td
                  .p_rating
                    {{player.pRating | percentage}}

The above example works, I'm just not sure if it's the best way of obtaining what I want to achieve? Should I try a filter or a switch instead? Or, is this 'acceptable'?


So, i'm taking commented advice, but I've gone wrong somewhere. I'm trying to use a predicate function within the filter: It seems I cannot pass in player from the same line as the repeat to filter by player.id.. Should i do a for loop over players within team...?

roster(ng-repeat="player in team.playerProfiles | orderBy: '-pRating' | limitTo:1 | filter:criteriaMatch(team, player)")
    .row
      .col-xs-1.col-sm-1.col-md-1.rosterCheck-col
      .col-xs-7.col-sm-7.col-md-7
        %table
           %tr
             %td
              .p_rating
                {{player.pRating | percentage}}

then, in my controller:

$scope.criteriaMatch = function( team, player ) {
  if (team.selected)
    return player.id == team.selected.playerId;
    };
  else 
    return player.id
};

1 个答案:

答案 0 :(得分:0)

roster(ng-repeat="player in team.playerProfiles | orderBy: '-pRating' | limitTo:1 | filter:team.selected.playerId)")

根据你已经拥有的东西,它可能没有你想象的那么复杂。您只需按过滤器中的selected.playerId内联过滤即可。