Search code examples
javascriptangularjsselecthtml-entitiesng-options

How to add HTML entities in Angular select with ng-option


My question is somehow related to this answer, although slightly different.

What I would like to achieve is to get HTML entities parsed from a string passed to a select with ng-options. So given these data:

$scope.myOptions = [{
   text: '10.00 €',
   val: 10
},{
   text: '25.00 €',
   val: 25
},{
   text: '50.00 €',
   val: 50
}];

And this template:

<select class="form-control" ng-model="desiredAmount" 
        ng-options="opt.val as opt.text for opt in myOptions">
</select>

I would like the &euro; entity to be displayed as €, while here this does not happen (and I can understand why, as Angular correctly interprets my data as a simple string). Is it possible to solve this?

Here's a jsbin I have made to isolate my problem.

PS - I know that I can achieve it using

<option ng-repeat="opt in myOptions">{{opt.text}} &euro;</option>

But this arises another problem with the appearance of a first empty option which is why I'd like to stick to the ng-option method, and in any case I would like to know if it is even possible to get a string parsed when using ng-option.


Solution

  • Use $sce, to format the euro sign.

    in HTML:

      <select>
          <option ng-repeat="opt in myOptions" ng-bind-html="htmlAdText(opt.text)">{{opt.text}}</option>
      </select>
    

    in JS:

      $scope.desiredAmount = $scope.myOptions[0].text;
    
      $scope.htmlAdText = function(text){
        return $sce.trustAsHtml(text);
      }
    

    Don't forget to inject $sce into your controller.

    http://jsbin.com/tijevebiya/2/edit?html,js,output