简体   繁体   中英

AngularJS conditional ng-option

I have an app angular that can be translate both in french and english. I'm using angular translate to do that. The problem is: I receive an array of object from an API and in those object, I have a property bookConditionEn and a property bookConditionFr and other like ids.

In a select input , I want to display bookCondition depending by the current language.

In the controller, I can get the current language with the $translate service

            vm.getCurrentLanguage = function() {
                return $translate.use();
            }

So, I wonder if in the view I could use a condition in the ng-option.

    <select 
      ng-options="bookCondition.BookCondition for bookCondition in bookCtrl.bookConditions"
      ng-model="bookCtrl.bookConditions" 
      name="Condition" class="form-control" 
    ></select>

You can use conditionals to show/hide options by changing the way you are creating the <select> :

<select ng-options=ng-model="bookCtrl.bookConditions" name="Condition" class="form-control">
    <option 
        ng-repeat="bookCondition.BookCondition for bookCondition in bookCtrl.bookConditions"
        ng-if="vm.getCurrentLanguage==bookCondition.language"
    >
</select>

I didn't quite understand how you have your JSON set up so I am assuming you have a property that contains the language (bookCondition.language). You can compare this against the user's currently-selected language which is returned by your vm.getCurrentLanguage . By the way, I suggest changing that from a function to just be a variable like this:

vm.currentLanguage = $translate.use();

This should be all you need to do to specify options in a conditional manner.

It worked your way

                <select ng-model="bookCtrl.bookCondition" name="Condition" class="form-control">
                    <option ng-if="bookCtrl.getCurrentLanguage() === 'en'" ng-repeat="bookCondition in bookCtrl.bookConditions" value="{{bookCondition}}">{{bookCondition.BookCondition}}</option>
                    <option ng-if="bookCtrl.getCurrentLanguage() === 'fr'" ng-repeat="bookCondition in bookCtrl.bookConditions" value="{{bookCondition}}">{{bookCondition.BookConditionFr}}</option>
                </select>

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