如何检查变量 trusted as HTML 在 AngularJS 中是否为空

How to check if variable trusted as HTML is empty in AngularJS

我有这种情况:

<div ng-bind-html="model"></div>
<div ng-if="!model">Echo me if model is empty</div>

在控制器中:

model = $sce.trustAsHtml(model);

只有当 model 是(在信任它之前)是空字符串时,我如何才能渲染第二个 <div>?我尝试了 ng-if="!model"ng-if="model == ''" 但这些都不起作用。

正如@MMhunter 所说,它应该工作(如果model 是空字符串)。我没有包括一些细节,因为我认为这些不相关。

基本上,model 是通过 RESTful 服务获取的,空模型在数据库中保存为 null。因此,!modelmodel == '' 都不起作用。现在,ng-if 是:

<div ng-if="model == '' || model == null">Echo me if model is empty</div>

而且有效。

结论: $sce.trustAsHtml(str) 保留了 null 值(以及 undefined 和空字符串)。 AngularJS 来源:

function trustAs(type, trustedValue) {
  var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  if (!Constructor) {
    throw $sceMinErr('icontext',
        'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
        type, trustedValue);
  }
  if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
    return trustedValue; // <<< THIS IS RESPONSIBLE >>>
  }
  // All the current contexts in SCE_CONTEXTS happen to be strings.  In order to avoid trusting
  // mutable objects, we ensure here that the value passed in is actually a string.
  if (typeof trustedValue !== 'string') {
    throw $sceMinErr('itype',
        'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
        type);
  }
  return new Constructor(trustedValue);
}