如何将ngOptions用于包含HTML实体的字符串?

Jus*_*808 8 html javascript angularjs angularjs-directive ng-options

我正在使用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")
Run Code Online (Sandbox Code Playgroud)

如何才能正确显示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}}")
Run Code Online (Sandbox Code Playgroud)

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

scn*_*iro 10

你可以解决这种情况的方法是使用ng-repeat沿ng-bind-html(包含ngSanitize代替)ng-options.这是一个有效的例子

var app = angular.module('app', ['ngSanitize']);
Run Code Online (Sandbox Code Playgroud)
<option ng-repeat="options in options" ng-bind-html="options.text" value="{{options.text}}"></option>
Run Code Online (Sandbox Code Playgroud)

JSFiddle Link - 工作演示

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

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

JSFiddle Link - ng-options演示

  • htmlDecode不适用于标记,只适用于html实体.我希望这种技术可以让我使用ng-options并在国家列表选择中插入一个标志图标. (2认同)

Ste*_*ell 6

基于其他答案,您可以使用过滤器执行此操作,并获得继续使用的好处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);
  }
});
Run Code Online (Sandbox Code Playgroud)

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

ng-options="o.id as o.label | decoded for o in options"
Run Code Online (Sandbox Code Playgroud)

我很惊讶这有用,但它在1.3.20中为我做了,它比其他解决方案更优雅!

但这样做可能会很昂贵.这里优化了es6版本的过滤器:https://gist.github.com/DukeyToo/ba13dbca527f257a6c59