【问题标题】:ng-if and check for a non-empty, non-null objectng-if 并检查非空、非空对象
【发布时间】:2015-08-12 11:42:05
【问题描述】:

我正在尝试这个:

<select ng-disabled="!items" class="form-control" ng-model="selected" ng-options="key as value for (key , value) in items">
    <option ng-if="items" value="">All Items</option>
</select>

但有项目时All Items选项不显示。

注意:问题出在ng-if,没有别的原因。

演示: http://plnkr.co/edit/jarknWGYXiHdGIWNtMvC?p=preview

【问题讨论】:

  • 您可以在&lt;option&gt; 上使用ng-repeat 而不是ng-options
  • @SergioTulentsev 我知道,但这个问题是关于ng-if 的替代方案,或者是在不使用ng-repeat 而不是ng-options 的情况下解决此问题的方法。谢谢!
  • 或者,只需将您的虚拟选项添加到 items 数组
  • 您可以使用ng-show 替代ng-if
  • 你是什么意思,“ng-if替代”?这使它成为"XY question"

标签: angularjs select angular-ng-if


【解决方案1】:

你可以像这样检查对象id是否为空

$scope.isEmpty = function (obj) {
for (var i in obj) if (obj.hasOwnProperty(i)) return false;
return true;
};

在视图中你可以这样做:

 <option ng-show="!isEmpty(items)">All Items</option>

ng-if 在选项标签中不起作用——这会发生,因为 select 元素在 DOM 树上比带有 ng-if 的 null 选项更高,所以它会首先编译。 see the angular source

【讨论】:

  • 我觉得angular或者jquery中应该有这个功能。没有吗?
  • 在 angular 中可能有 angular.equals({}, $scope.items)
【解决方案2】:

这对我来说是个不错的选择:

angular
  .module('myApp')
  .filter('empty', function() {
    return function(obj) {
      return obj === null || angular.equals({}, obj)
    }
  })
<span ng-if="items|empty">0 items</span>

将函数添加为过滤器并使用 Angular 进行测试。

感谢@Hmahwish 的启发。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 2013-04-29
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多