简体   繁体   English

选择 Angularjs 中的预选选项

[英]Pre-selected option in select Angularjs

I have tried everything in the book.我已经尝试了书中的所有内容。 I just cant get option 1 value="1" User to be preselected.我只是无法预选选项 1 value="1" User。 I am using angular website.我正在使用角网站。 If I remove ng-model="type" it gets preselected.如果我删除 ng-model="type" 它会被预选。 but just cant get it working with ng-model="type" in it.但只是不能让它与 ng-model="type" 一起工作。

<div class="form-group">
   <select name="type" id="type" class="form-control" ng-model="type">
       <option value="1" selected="selected">User</option>
       <option>Broadcasters</option>
   </select>
</div>

Simple solution: You can use ng-selected directive简单的解决方案:您可以使用ng-selected指令

<div class="form-group">
   <select name="type" id="type" class="form-control" ng-model="type">
      <option value="1" ng-selected="true">User</option>
      <option>Broadcasters</option>
   </select>
</div>

It happens because you pass Number to ng-model, instead input has string as value.发生这种情况是因为您将 Number 传递给 ng-model,而不是输入将字符串作为值。 Also it will work without ng-selected directive if you will pass String to ng-model.如果您将字符串传递给 ng-model,它也可以在没有 ng-selected 指令的情况下工作。

Better to use: ng-options更好用: ng-options

<select ng-options="type as type.label for type in types" ng-model="currentType"></select>

$scope.types = [{
            id: 1,
            label: 'User'
        }, {
            id: 2,
            label: 'Broadcasters'
        }];

$scope.currentType = $scope.types[0]; //default type

Use the ng-value directive for numerical option values:对数字选项值使用ng-value 指令

 <script src="//unpkg.com/angular/angular.js"></script> <body ng-app ng-init="type=1"> <div class="form-group"> <select name="type" id="type" class="form-control" ng-model="type"> <option ng-value="1">User</option> <option ng-value="2">Broadcasters</option> </select> <p>type = {{type}}</p> </div> </body>

You can use ng-model with ng-init to set the default selected value,您可以使用 ng-model 和 ng-init 来设置默认选定值,

<select name="type" ng-model="selected" ng-init="selected='1'" id="type" class="form-control" ng-model="type">

DEMO演示

 var app = angular.module('myApp', []); app.controller('AppCtrl', function($scope) { });
 <!DOCTYPE html> <html> <head> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <div ng-app="myApp" ng-controller="AppCtrl"> <div class="form-group"> <select name="type" ng-model="selected" ng-init="selected='1'" id="type" class="form-control" ng-model="type"> <option value="1" >User</option> <option>Broadcasters</option> </select> </div> </div> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM