我有一个绑定(bind)到对象的 ng-options 选择。仅当将其设置为字符串时,以编程方式设置 ng-model 才能正常工作(更新选择)。如果我将 ng-model 设置为整数,则不起作用。我真的不想进行这种转换。这是唯一的方法吗?
<div ng-controller="MyCtrl">
<select ng-options="id as name for (id, name) in items" ng-model="selected"></select>
<div>Selected ID: {{selected}} </div>
<button ng-click="setSelected(1)">Set Selected to ID 1 as Integer</button>
<button ng-click="setSelected('1')">Set Selected to ID 1 as String</button>
<div>Programmatically setting the ng-model as string sets the dropdown but not as integer.</div>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.items = {1: 'a', 2: 'b', 3:'c'};
$scope.selected = null;
$scope.setSelected = function(id) {
$scope.selected = id;
}
}
最佳答案
已编辑
如果您正在寻找快速但肮脏的解决方案,那么当您以编程方式设置模型值时,可以尝试使用 toString
。有关问题核心的详细信息,请参阅@ExpertSystems 答案。
$scope.setSelected = function(id) {
$scope.selected = id.toString();
}
关于angularjs - 以编程方式选择绑定(bind)到对象数据源的 ng-options,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23556455/