问题
I am using an ng-repeat to iterate over objects for displaying in Angular and each of these objects contains a select element containing a property of the object.
I want to filter options based off the selected value for each of the objects' other properties (whew, this is harder to explain than I thought) but the problem is that these are Breeze entities and if I use the traditional method Angular provides the stack throws an overflow exception due to the cyclic nature of Breeze entities.
I have found a good example by Ward on how to create a more static function to handle the filtering, but I am trying to make it more dynamic and am struggling -
In the view I have a list of available fighters, which should be filtered by a fights' weight class, so for each fight in the ng-repeat's fights there is a weight class selector, and two fighter selectors -
Attempt 1 -
<select
ng-model="fight.firstFighter"
ng-options="f.fullName for f in fighters | filter: fighterFilter">
</select>
<select
ng-model="fight.weightClass"
ng-options="w.fullName for w in weightClasses">
</select>
$scope.fighterFilter = function (fighter) {
var fight = ???;
return fight.weightClass ?
-1 != fighter.weightClass === fight.weightClass :
true;
};
I have tried sending nothing as shown, but the problem is it only sends the fighter's value as it iterates through each available fighter, so I can't get the value of the fight.weightClass.
Any idea of how to get the context of fight and the fighter I am iterating over? Or a better approach to filtering this way?
Fighters Structure
Fighter
- Id
- Name
- WeightClassId
- WeightClass (navigation property)
Fight
- FirstFighter
- SecondFighter
- WeightClassId
- WeightClass (navigation property)
WeightClass
- Id
- Weight
- Description
- FullName
Edit
I have been able to filter results for s single fight without a problem, the problem is how to dynamically handle this on a per fight basis in the same view under the ng-repeat directive. I cannot get the context of 'fight' and 'fighter' to compare whether the 'weight class' value of both entities match.
回答1:
Filter can take a expression
as an Object
in the format of {fieldName:value}
.
You can use | filter: {WeightClassId:fight.WeightClass.Id}
to achieve what you want.
<li ng-repeat="fight in fights">
<h4>{{ fight.number }}</h4>
Weight Class:
<select ng-model="fight.WeightClass" ng-options="w.Name for w in weightClasses"></select>{{ fight.WeightClass.Name }}
<br/>First Fighter
<select ng-model="fight.FirstFighterId" ng-options="f.Name for f in fighters | filter: {WeightClassId:fight.WeightClass.Id}"></select><span>{{ fight.FirstFighter.Name }}</span>
<br/>Second Fighter
<select ng-model="fight.SecondFighterId" ng-options="f.Name for f in fighters| filter: {WeightClassId:fight.WeightClass.Id}"></select><span>{{ fight.SecondFighter.Name }}</span>
</li>
Demo
来源:https://stackoverflow.com/questions/18277725/dynamic-select-element-filtering-in-angular