【问题标题】:How to check if variable trusted as HTML is empty in AngularJS如何检查AngularJS中作为HTML信任的变量是否为空
【发布时间】:2016-08-11 08:12:57
【问题描述】:

我有这种情况:

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

在控制器中:

model = $sce.trustAsHtml(model);

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

【问题讨论】:

  • 您提供的代码应该可以工作,因为如果 $sce.trustAsHtml 为空字符串、null 或未定义,它将返回值本身。我认为需要更多信息。如果你不想在 div 为 null 或 undefined 时显示它,你应该使用model === ''

标签: angularjs binding angular-template


【解决方案1】:

正如@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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-05
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    相关资源
    最近更新 更多