选择角度中的预选选项

时间:2017-07-09 19:03:49

标签: angularjs

我已经尝试了书中的所有内容。我只是无法获得选项1值=“1”用户被预先选择。我正在使用有角度的网站。如果我删除ng-model =“type”,它会被预先选中。但是不能让它使用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>

3 个答案:

答案 0 :(得分:1)

简单解决方案:您可以使用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>

这是因为您将Number传递给ng-model,而输入将string作为值。如果你将String传递给ng-model,它也可以在没有ng-selected指令的情况下工作。

最好使用: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

答案 1 :(得分:0)

您可以将ng-model与ng-init一起使用来设置默认选择值

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

<强>样本

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {
 
});
&#13;
<!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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用ng-value directive作为数字选项值:

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

相关问题