ng-selected不在angularjs中选择

时间:2018-05-30 06:06:59

标签: html angularjs

我是Angularjs.的新手。我正在尝试使用静态值为angularjs中的select设置默认值。我没有使用任何ng-repeat或options.But我无法使用ng-selected.Everywhere设置默认值我找到的解决方案仅适用于ng-options而不适用于静态值。

这是我的HTML

    <select name="gender" id="gender" data-ng-model="gender" ng-
    selected=="Male">
    <option value="">Select Gender</option>
    <option value="Male">Male</option>
    <option value="Female">Female</option>
    </select>

谁能告诉我哪里做错了?

4 个答案:

答案 0 :(得分:2)

您可以在控制器中设置ng-model的默认值,尝试在控制器中添加

$scope.gender = 'Male';

答案 1 :(得分:2)

According to official DOCSng-selected适用于options,不适用于select

您应该将boolean设为ng-selected

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="">

<select ng-init="mySel = true">
  <option>Select</option>
  <option value="male" ng-selected="mySel">Male</option>
  <option value="female">Female</option>    
</select>

</body>
</html>

请使用ng-model

查看此示例

执行此操作的首选方法是使用ng-model而不使用ng-selected

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp" >


<select name="gender" id="gender" ng-model="gender" ng-controller="myCtrl">
    <option value="">Select Gender</option>
    <option  value="Male">Male</option>
    <option value="Female">Female</option>
  </select>




<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
     $scope.gender = "Male" 
});
</script>

</body>
</html>

答案 2 :(得分:1)

您可以使用ng-init指令。正如Sraven所说,ng-selected必须使用<option>标记。

My Example

<select name="gender" id="gender" data-ng-model="gender" ng-init="gender='Male'">
    <option value="">Select Gender</option>
    <option value="Male">Male</option>
    <option value="Female">Female</option>
</select>

答案 3 :(得分:1)

ng-selected指令只能在<option>标记

中使用

检查以下代码

  <select name="gender" id="gender" data-ng-model="gender" >
    <option value="">Select Gender</option>
    <option ng-selected="true" value="Male">Male</option>
    <option value="Female">Female</option>
    </select>