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

标签 angularjs

我正在尝试从选择下拉列表中过滤掉“空”结果。 到目前为止,我只使用常规 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/

相关文章:

javascript - Angular 2 中处理 click 和 clickOutside 事件执行优先级的最佳方法?

angularjs - 如何在 Angular.js 中比较时间?

javascript - 重新编译文档中新加载的正文元素 - Angular

javascript - 将对象 ID 传递到 session 存储

javascript - 无法将数据从 Controller 正确绑定(bind)到自定义指令模板,Angular

javascript - ng-repeat 的意外结果

javascript - angularjs - 带搜索参数的路由

javascript - 不显示以前的语句 (ng-show)

javascript - 使用 Bootstrap 和 AngularJS 进行表单验证

javascript - 如何从自定义指令获取链接href?