javascript - ng-model 具有字符串值和 ng-option 整数

标签 javascript angularjs

这是我的 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/

相关文章:

javascript - 验证 php 和 javascript 中一个字段的值大于另一个字段的值

javascript - flot.navigate 拖动开始/结束事件缺失

javascript - 是否可以使用 CSS 分配数据属性?

angularjs - Angular-ui-bootstrap 模式不传回结果

angularjs - Angular JS - 服务返回函数代码而不是函数返回值

angularjs - 用咕噜声构建 Angular 应用程序,应用程序无法加载

javascript - 无法将项目添加到数组

javascript - 解析后台作业未正确查询所有用户

javascript - 在 AngularJS 中使用来自不同 Controller 的 $scope 函数

javascript - AngularJS 和 i18n : apply ng-repeat filters after translating list items properties