Angular ng-if inside option element and ng-repeat

2019-03-25 12:44发布

问题:

I have select element which should list available currencies. Default currency should have prefix "Default" before its name. For some reason, that prefix is showing for all currencies in the list.

Test HTML:

<div ng-app="testApp">
  <div ng-controller="MainCtrl">
     <select>
        <option ng-repeat="rate in rates track by $index">
            <span ng-if="rate.is_default">Default</span>
            <span>{{rate.name}}</span>
        </option>
     </select>
  </div>
</div>

TEST JS:

var app = angular.module("testApp", []);

app.controller("MainCtrl", function($scope){

$scope.rates = [
    { 'name': 'dolar', 'is_default': true},
    { 'name': 'pound', 'is_default': false},
    { 'name': 'euro', 'is_default': false}
];

});

jsFiddle

回答1:

You can't use HTML tags in an option tag but you can do something like this:

<option ng-repeat="rate in rates track by $index">
    {{ rate.is_default ? 'default' : '' }} {{rate.name}}
</option>

Fiddle