Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-if inside option element and ng-repeat not working

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

like image 802
NenadPavlov Avatar asked May 20 '14 09:05

NenadPavlov


People also ask

How do you condition in NG-repeat?

You can add condition using ng-if also and this is effective too. You can apply any condition to your list using ng-if attribute. In below example, I have put condition where Age > 20 and IsActive is true. ng-repeat will fetch all records which full fill this scenario.

What is the difference between ng-repeat and Ng-options?

ng-options is the directive which is designed specifically to populate the items of a dropdown list. One major advantage using ng-options for the dropdown is, it allows us to pass the selected value to be an object. Whereas, using ng-repeat the selected value can only be string.

Can we use ngIf and Ng-show together?

ng-if is better in this regard. Using it in place of ng-show will prevent the heavy content from being rendered in the first place if the expression is false. However, its strength is also its weakness, because if the user hides the chart and then shows it again, the content is rendered from scratch each time.

Which is better Ng-if or NG-show?

ng-if can only render data whenever the condition is true. It doesn't have any rendered data until the condition is true. ng-show can show and hide the rendered data, that is, it always kept the rendered data and show or hide on the basis of that directives.


1 Answers

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

like image 56
Dieterg Avatar answered Oct 21 '22 17:10

Dieterg