在控制器中给出此代码:
$scope.selectedParam = 95
$scope.param = {
value: {
95: "John",
193: "Doe",
}
}
这样的模板
<select
ng-model="selectedParam"
ng-options="key as value for (key, value) in param.value track by key">
</select>
如何从模型中选择项目?
以下是 jsfiddle that is not working 的示例 这是 one that work 。
为什么第一个例子不起作用。有什么方法可以使它工作吗?我需要数字作为选项对象的键,而不是值。否则我需要在我的应用程序中重构大量的代码。
答案 0 :(得分:4)
避免将整数用作JSON密钥,JSON要求所有密钥必须是字符串。然后,如果您删除该轨道,您可以看到它再次工作。 HTML:
<select
ng-model="selectedParam"
ng-options="key as value for (key, value) in param.value"></select>
使用Javascript:
$scope.selectedParam = "95"
$scope.param = {
value: {
"95": "John",
"193": "Doe",
}
}
答案 1 :(得分:-1)
只需将“selectedParam”更改为字符串类型而不是整数,如下所示: -
控制器
$scope.selectedParam = "95";
在视图中
<select ng-model="selectedParam">
<option ng-repeat="(key, value) in param.value track by key" value="{{key}}">{{ value}}</option>
</select>
(function(angular) {
'use strict';
angular.module('defaultValueSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.selectedParam = "95";
$scope.param = {
value: {
95: "John",
193: "Doe",
}
}
}]);
})(window.angular);
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
</head>
<body ng-app="defaultValueSelect">
<div ng-controller="ExampleController">
<form name="myForm">
<select ng-model="selectedParam">
<option ng-repeat="(key, value) in param.value track by key" value="{{key}}">{{ value}}</option>
</select>
</form>
</div>
</body>
</html>