Home selected boolean value on angular ng-options
Reply: 2

selected boolean value on angular ng-options

Anastasia Sitnina
1#
Anastasia Sitnina Published in 2018-01-12 17:44:34Z

The boolean value assigned to the model doesn't pre-select the corresponding option - shows first an empty option instead:

Select:

<select data-ng-model="scriptData.privacy" data-ng-options="privacyOption.value as privacyOption.label for privacyOption in privacyOptionsSelect track by privacyOption.value"></select>

Options in the controller:

$scope.privacyOptionsSelect=[
            {
                label:'Registered users only can view this',
                value: false
            },
            {
                label:'Anyone with the link can view this',
                value: true
            }
        ];

scriptData.privacy is set to false.

Nikolaj Dam Larsen
2#
Nikolaj Dam Larsen Reply to 2018-01-12 18:31:28Z

You should be careful when using the ngOptions expression with the format:

select as label for value in array

together with track by. This is because track by is applied to the value assigned to your ngModel, so if your selection is in the form privacyOption.value, the track by expression is actually applied to the value. This is the reason it doesn't successfully select the initial value.

To fix this you have two options. You can either just skip track by. This would work:

<select data-ng-model="scriptData.privacy" 
        data-ng-options="privacyOption.value as privacyOption.label for privacyOption 
            in privacyOptionsSelect"></select>

Or you could change the select as-expression to select the entire privacyOption-object. This would work as well (note the ngModel-directive changed as well):

<select data-ng-model="scriptData"
        data-ng-options="privacyOption as privacyOption.label for privacyOption 
            in privacyOptionsSelect track by privacyOption.value"></select>

For a full (and probably better) explanation, I recommend the ngOptions documentation.

Ruchira Chamara
3#
Ruchira Chamara Reply to 2018-01-12 17:53:30Z

try ng-repeat instead of ng-options by applying the ng-repeat to option elements inside the select.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300946 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO