简体   繁体   中英

Set default value for select and option tag in Angular

So I have angular code like this

<select class="form-control" ng-model="ctrl.selectedProvider">
    <option value="">Please select a provider</option>
    <option ng-repeat="provider in ctrl.providers" ng-value={{provider.id}}>
        {{provider.description}}
    </option>
</select>

The data is like this

providers = [{
     id: 1,
     description: provider1
},{
     id: 2,
     description: provider2
}]

If there's only have one element in ctrl.providers, I want to set the default value of the select tag to this provider. Otherwise, I want to keep it to "Please select a provider" and let the user select the provider he wants. I have googled that and found ng-init, but I think it's not useful for my case. Any ideas? Thanks

Use ng-options to create the <option> tags and check data length to assign model if applicable

 angular.module('app', []) .controller('MainCtrl', function() { this.providers = [{ id: 2, description: 'provider2' }]; if (this.providers.length === 1) { this.selectedProvider = this.providers[0] } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.js"></script> <div ng-app="app" ng-controller="MainCtrl as ctrl"> <select class="form-control" ng-model="ctrl.selectedProvider" ng-options="o.id as o.description for o in ctrl.providers track by o.id"> <option value="">Please select a provider</option> </select> </div> 

I think what you have will work, just need to adjust your code a little: (Example below)

 var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { var ctrl = this; // Uncomment to see result //ctrl.selectedProvider = null; //ctrl.selectedProvider = ""; ctrl.selectedProvider = 1; //ctrl.selectedProvider = 2; ctrl.providers = [{ id: 1, description: "provider1" },{ id: 2, description: "provider2" }]; }); 
 <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <link rel="stylesheet" href="style.css" /> <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script> <script src="app.js"></script> </head> <body ng-controller="MainCtrl as ctrl"> <select class="form-control" ng-model="ctrl.selectedProvider"> <option value="">Please select a provider</option> <option ng-repeat="provider in ctrl.providers" ng-value={{provider.id}}> {{provider.description}} </option> </select> </body> </html> 

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