我正在尝试从选择下拉列表中过滤掉“空”结果。
到目前为止,我只使用常规 html <select>
+ <option>
与 ng-repeat
并以这种方式排除空结果:
<option ng-repeat="person in showCase.persons" ng-if="person.profiles">
{{person.profiles}}
</option>
这样我可以获得一个没有空/空“用户配置文件”的列表。
现在我开始使用ng-options
相反,因为列表包含带有对象的数组,
但我无法得到空结果 - ..当我使用 ng-if
时整体<select>
消失:
<select ng-model="profile_filter" ng-options="person.profiles for person in persons"
ng-if="person.profiles">
</select>
我的首要任务是内联执行,而不是在我的 Controller 中,因为有很多 <select>
页面中的对象,有些确实需要显示“null”结果。
我知道,这是一个非常基本的问题,但在过去的两个小时里它仍然让我陷入困境。
谢谢。
最佳答案
当您在选择上使用 ng-if 时,它会在选择上查找范围 person.profiles
上不存在的属性。 person.profiles for person in people
只是 ng-options
的表达式。
您可以在绑定(bind) Controller 之前过滤掉 Controller 本身的空值。或者创建一个过滤器或仅将过滤器表达式与现有的 Angular Core filter
一起使用。
示例:-
在你的 Controller 中定义一个函数,如果配置文件是假的(你可以根据需要将其明确化),则在范围上定义一个函数来删除,如果你返回真值,那么该项目将被添加为选项,否则它将被忽略:
$scope.removeNull = function(itm) {
return itm.profiles;
}
只需在 View 中使用它:-
<select ng-model="profile_filter"
ng-options="person.profiles for person in persons|filter:removeNull">
angular.module('app', []).controller('ctrl', function($scope) {
$scope.persons = [{
profiles: null
}, {
profiles: "prf1"
}, {
profiles: "prf2"
}, {
profiles: "prf3"
}, {
profiles: null
}, {
profiles: "prf4"
}]
$scope.removeNull = function(itm) {
return itm.profiles;
}
$scope.profile_filter = $scope.persons[1];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select ng-model="profile_filter" ng-options="person.profiles for person in persons|filter:removeNull">
</select>
{{profile_filter}}
</div>
关于angularjs - 在 ng-options 中使用 ng-if 来过滤空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27931643/