这是我的 JSON 数组:
array=[ {id:1, name:'A'} , {id:2, name:'B'} ]
在 ng-model 中,我设置的值可能是字符串
modelValue='1'
我有 ng-option
ng-option="option.id as option.name for option in array"
ng-model="modelValue"
但它没有显示 select 中 ng-model 的选定值
最佳答案
And in ng-model I am setting value which may be string like
您应该提供相同的 primitive or object type
给您$scope.modelValue
截至id
。这是首选方式。
只要 JSON array
正在动态获取并且不能保证类型一致性,那么您可以应用函数将其转换为设置为 $scope.modelValue
的类型
在 HTML 中
<select ng-model="modelValue" ng-options="getId(option.id) as option.name for option in myarray">
</select>
在 Controller 中
$scope.modelValue='1';
$scope.myarray=[ {id:1, name:'A'} , {id:2, name:'B'} ];
$scope.getId = function(id)
{
if(typeof $scope.modelValue == "string")
return String(id);
else if(typeof $scope.modelValue == "number")
return parseInt(id);
}
<强> COMPLETE EXAMPLE
另请参阅this回答
关于javascript - ng-model 具有字符串值和 ng-option 整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929302/