简体   繁体   中英

<select> with ng-model and static options (true/false)

I have a simple select element which I want to use to set a boolean value:

# JS; somewhere inside the controller
var vm = this;
vm.isAdmin = false;
return vm;

# HTML
<select ng-model="formCtrl.isAdmin">
    <option ng-value="true">Yes</option>
    <option ng-value="false">No</option>
</select>

Unfortunately, when loading the site, nothing is selected. I know I could use ng-repeat, but I don't want to because it seems unpractical to me.

UPDATE: While the possible duplicate has basically the same accepted answer (because it's the best way to achieve the desired behaviour), the question itself is different. I actually wanted to use hard-coded options, not ng-options/ng-repeat.

Why don't you use ng-options ?

<select ng-model="form.isAdmin" ng-options="o.value as o.name for o in options"></select>

options array in your controller:

$scope.options = [
    { 'name': 'Yes', 'value': true }, 
    { 'name': 'No', 'value': false }
];

Demo on JSFiddle


 var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', [function() { var vm = this; vm.isAdmin = false; vm.adminOptions = [{ val: true, name: 'Yes' }, { val: false, name: 'No' }]; }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp"> <div ng-controller="MyCtrl as form"> <select ng-model="form.isAdmin" ng-options="opt.val as opt.name for opt in form.adminOptions"> </select> {{form.isAdmin}} </div> </div> 

Use ng-options :

<select ng-model="form.isAdmin" 
        ng-options="opt.val as opt.name for opt in [{val:true,name:'Yes'},{val:false,name:'No'}]">
</select>

See this jsfiddle

You need to basically use the following syntax for your option tag (use ng-selected):

<select ng-model="formCtrl.isAdmin">
    <option ng-value="true" ng-selected="formCtrl.isAdmin">Yes</option>
    <option ng-value="false" ng-selected="!formCtrl.isAdmin">No</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