ngmodel不绑定选择标记

时间:2016-03-22 07:47:50

标签: javascript html angularjs

我将从服务中获取所选值为整数,并需要将其作为整数发回。请查看Plnkr代码

<!-- Working -->
<div ng-init="selectedvalue = '3'">
    <select ng-model="selectedvalue">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </select>
</div>
<!-- Not Working -->
<div ng-init="selectedvalue2 = 3">
    <select ng-model="selectedvalue2">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </select>
</div>
<!-- Not Working -->
<div ng-init="selectedvalue3 = 3">
    <select ng-model="selectedvalue3">
    <option value=1>1</option>
    <option value=2>2</option>
    <option value=3>3</option>
    <option value=4>4</option>
  </select>
</div>

https://plnkr.co/edit/R7QfJfy6m6IgHKL07tFI?p=preview

4 个答案:

答案 0 :(得分:2)

在ng-model中,您可以添加一个过滤器编号进行转换,如下所示:

ng-model="selectedvalue3 | number"

答案 1 :(得分:0)

select中的值被解释为字符串。

您必须使用字符串并在之前或之后转换/解析您的值。

答案 2 :(得分:0)

您可以按照此过程select as label for value in array更好地从控制器初始化值。

喜欢控制器:

$scope.selectedvalue3 = 30;
$scope.infos= [{age:21, name:"xx"},{age:20, name:"yyy"},{age:30, name:"zzz"},{age:40, name:"ppp"}];

并在HTML中:

<div>
     <select ng-options="info.age as info.age for info in infos" ng-model="selectedvalue3"></select>
</div>

其中age是整数值。它可能对你有帮助

答案 3 :(得分:0)

添加指令以将字符串解析为int。例如选择标记上的convert-to-number

<select ng-model="selectedvalue" convert-to-number>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

然后你可以

.directive('convertToNumber', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function(val) {
        return parseInt(val, 10);
      });
      ngModel.$formatters.push(function(val) {
        return '' + val;
      });
    }
  };
});