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

对着背影说爱祢 提交于 2019-12-05 03:03:51

A way you can solve this is to use ng-repeat along with ng-bind-html (included with ngSanitize) in place of ng-options. Here is a working example

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

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

JSFiddle Link - working demo

Furthermore, if you must use ng-options use the following helper function to decode your values first before binding

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

JSFiddle Link - ng-options demo

Building on the other answers, you can do this with a filter, and gain the benefit of continuing to use ng-options. Example filter:

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);
  }
});

Then you can apply the filter in the ng-options. For example:

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

I was surprised that this worked, but it did for me in 1.3.20, and it is more elegant than other solutions!

It can be expensive to do this though. Optimized es6 version of the filter here: https://gist.github.com/DukeyToo/ba13dbca527f257a6c59

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!