在ng-options中使用ng-if来过滤空结果

Dot*_*Bot 2 angularjs

我正在尝试从选择下拉列表中过滤掉"null"结果.到目前为止,我只使用常规html <select>+ <option>并以ng-repeat这种方式排除null结果:

<option ng-repeat="person in showCase.persons" ng-if="person.profiles">
{{person.profiles}}
</option>
Run Code Online (Sandbox Code Playgroud)

这样我就可以得到一个没有空/ null'用户配置文件'的列表.现在我开始使用了,ng-options因为列表包含带有对象的数组,但我无法得到null结果 - ..当我使用ng-if整个<select>消失时:

<select ng-model="profile_filter" ng-options="person.profiles for person in persons"  
ng-if="person.profiles">
</select>
Run Code Online (Sandbox Code Playgroud)

我的优先事项是内联而不是我的控制器,因为<select>页面中有很多对象,有些确实需要显示"null"结果.我知道,这是一个非常基本的问题,但仍然让我在最后2个小时内陷入困境.谢谢.

PSL*_*PSL 9

当您ng-if在选择上使用时,它会在选择中查找范围内person.profiles不存在的属性.person.profiles for person in persons仅仅是表达ng-options.

您可以在绑定之前从控制器本身过滤掉空值.或者创建一个过滤器或只使用现有角度核心的过滤器表达式filter.

例:-

在你的控制器中定义一个函数在范围上删除如果配置文件是假的(你可以根据需要使其显式),如果你返回truthy然后该项目将被添加为选项,否则它将被忽略:

$scope.removeNull = function(itm) {
    return itm.profiles;
  }
Run Code Online (Sandbox Code Playgroud)

并在视图中使用它: -

<select ng-model="profile_filter"
    ng-options="person.profiles for person in persons|filter:removeNull">
Run Code Online (Sandbox Code Playgroud)

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];
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)