option not selected angularjs select

option not selected angularjs select

本文关键字:select angularjs selected not option      更新时间:2023-09-26

您好,我正在尝试使用字符串值

选择选项中的数组项

这是我的html:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-controller="AppCtrl" ng-app="myApp">
  <select ng-model="gender" ng-options="g.vl as g.lbl for g in genders track by g.vl">
  </select>
</body>
</html>
JS CODE:
var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {
  $scope.genders = [ {lbl: 'Male', vl: 'male'}, {lbl: 'Female', vl: 'female'}];
  $scope.gender = 'female';
});

这是工作很好,当我删除轨道by,它选择初始值,但我需要使用轨道by,所以我可以使用从DB的值(当使用轨道由它选择空选项)..有办法解决这个问题吗?(不循环选项并比较初始值)。下面是代码片段http://jsbin.com/qixad/4/edit

当你使用track by时,angular将使用在track中通过表达式识别的属性来确定一致性。因此,要初始化性别,所需要做的就是用定义了vl属性的对象初始化它:

$scope.gender = {vl:'female'}; //OR
$scope.gender = $scope.genders[1];

另外,ng-options表达式中的关键字必须是模型本身。

<select ng-model="gender" ng-options="g as g.lbl for g in genders track by g.vl">
</select>

JS Bin Demo