如何将 ngOptions 与包含 HTML 个实体的字符串一起使用?

How do I use ngOptions with a string that contains HTML entities?

我正在使用 ngOptions 构建一个选择菜单,但我的一个标签中有一个 HTML 实体 &。标签显示为 Books & Stuff 而不是 Books & Stuff。我的玉是这样的:

select(ng-show="isType === 'select'", id="{{id}}", ng-model="model", ng-options="o.id as o.label for o in options")

如何让 HTML 个实体正确显示?


更新

我正在尝试 sal 的回答:

select(ng-show="isType === 'select'", id="{{id}}", ng-model="model")
  option(ng-repeat="o in options", ng-bind-html="o.label", value="{{o.id}}")

这会显示正确的 html 实体,但不再根据模型选择正确的选项。例如,参见 http://jsfiddle.net/ucLvjvkn/1/

解决此问题的一种方法是使用 ng-repeatng-bind-html(包含在 ngSanitize 中)代替 ng-options。这是一个工作示例

var app = angular.module('app', ['ngSanitize']);

<option ng-repeat="options in options" ng-bind-html="options.text" value="{{options.text}}"></option>

JSFiddle Link - 工作演示

此外,如果您必须使用 ng-options,请在绑定之前先使用以下辅助函数解码您的值

function htmlDecode(input) {
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes[0].nodeValue;
}

JSFiddle Link - ng-options 演示

在其他答案的基础上,您可以使用过滤器来执行此操作,并获得继续使用 ng-options 的好处。过滤器示例:

myApp.filter('decoded', function() {
  "use strict";

  function htmlDecode(input) {
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes[0].nodeValue;
  }

  return function(input) {
    return htmlDecode(input);
  }
});

然后您可以在 ng-options 中应用过滤器。例如:

ng-options="o.id as o.label | decoded for o in options"

我很惊讶这有效,但它在 1.3.20 中对我有效,而且比其他解决方案更优雅!

虽然这样做的成本很高。此处优化了 es6 版本的过滤器:https://gist.github.com/DukeyToo/ba13dbca527f257a6c59