简体   繁体   中英

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 .

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

As regards as euro problem, you can also use a filter to display the value. This filtre is currency and put all value in this format : $0.00. Moreover you can also change the currency symbol.

You can do it like this :

{{opt.val | currency:"€"}}

You can find more information here :

http://docs.angularjs.org/api/ng.filter:currency

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM