如何在 ng-repeat 过滤器中添加动态列
How to add dynamic column in ng-repeat filter
是否可以在 ng-repeat
过滤器中添加动态列 filter:{'Is'+dType.Name:true}
?
<option ng-repeat="option in mainCtrl.Maps | filter:{'Is'+dType.Name:true}" ng-value="option.Id">{{option.Name}}</option>
不,Angular 会抛出错误。但是您可以改用函数,该函数可以使用动态属性,例如:
<option ng-repeat="option in mainCtrl.Maps | filter:filterFn" ng-value="option.Id">{{option.Name}}</option>
在控制器中:
$scope.filterFn = function(option) {
var propName = 'Is' + $scope.dType.Name; // assuming that dType is somewhere in the scope
return option[propName] === true; // this replaces the shorthand filter in the ng-repeat
}
编辑(由于不属于原始问题的其他详细信息):
如果您想将附加参数传递给您的过滤器函数,您可以使用我在以下 SO 答案中找到的内容:How to use parameters within the filter in AngularJS?
根据您的情况进行了调整:
<option ng-repeat="option in mainCtrl.Maps | filter:filterFn(dType)" ng-value="option.Id">{{option.Name}}</option>
在控制器中:
$scope.filterFn = function(dType) {
return function (option) {
var propName = 'Is' + dType.Name; // dType is passed as parameter
return option[propName] === true;
};
};
简而言之,您的过滤函数必须 return 具有 Angular 期望的签名的函数(具有一个参数的函数:ng-repeat
的元素),但是由于包装它还可以处理其他参数。
是否可以在 ng-repeat
过滤器中添加动态列 filter:{'Is'+dType.Name:true}
?
<option ng-repeat="option in mainCtrl.Maps | filter:{'Is'+dType.Name:true}" ng-value="option.Id">{{option.Name}}</option>
不,Angular 会抛出错误。但是您可以改用函数,该函数可以使用动态属性,例如:
<option ng-repeat="option in mainCtrl.Maps | filter:filterFn" ng-value="option.Id">{{option.Name}}</option>
在控制器中:
$scope.filterFn = function(option) {
var propName = 'Is' + $scope.dType.Name; // assuming that dType is somewhere in the scope
return option[propName] === true; // this replaces the shorthand filter in the ng-repeat
}
编辑(由于不属于原始问题的其他详细信息):
如果您想将附加参数传递给您的过滤器函数,您可以使用我在以下 SO 答案中找到的内容:How to use parameters within the filter in AngularJS?
根据您的情况进行了调整:
<option ng-repeat="option in mainCtrl.Maps | filter:filterFn(dType)" ng-value="option.Id">{{option.Name}}</option>
在控制器中:
$scope.filterFn = function(dType) {
return function (option) {
var propName = 'Is' + dType.Name; // dType is passed as parameter
return option[propName] === true;
};
};
简而言之,您的过滤函数必须 return 具有 Angular 期望的签名的函数(具有一个参数的函数:ng-repeat
的元素),但是由于包装它还可以处理其他参数。