AngularJS不会绑定到选择列表中的数值 [英] AngularJS not binding to numeric value in select list

查看:167
本文介绍了AngularJS不会绑定到选择列表中的数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一标有选择选项的现有标签现有的选择标记,例如:

I have an existing select tag with existing option tags, one marked "selected", for example:

<div class="form-group">
  <label class="control-label">Test</label>
  <select ng-model="vm.testNumber">
    <option>Choose...</option>
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3" selected>three</option>
  </select>
  <p class="help-block">{{vm.testNumber}}</p>
</div>

角被正确绑定到模型,并在页面加载时,但选项3未选择在帮助块吐出3。它结合并显示了3个,如果我用文字上的每个选项的值属性作为选择,但如果它不是一个数值。相反,它插入一个选项在选择列表的顶部:

Angular is binding to the model correctly and spits out "3" in the help block when the page loads, but option 3 is not selected. It binds and shows 3 as selected if I use text for the value attributes on each option, but not when it's a numerical value. Instead it inserts an option at the top of the select list:

<option value="? number:3 ?"></option>

我在做什么错了?

What am I doing wrong?

推荐答案

原来你需要添加一个指令正确,使这项工作。 @ codeninja.sj的回答结束了1替换一,二与2等。在的机制的文档,最后一个例子有这个指令,转换到数字

Turns out you need to add a directive to make this work correctly. @codeninja.sj's answer ends up replacing 'one' with 1, 'two' with 2, etc. In the documention, the last example has this directive, convert-to-number

angular.module('app').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;
        });
    }
};
});

的文档中的其他例子没有为我工作。

None of the other examples in the documentation worked for me.

更新 @ codeninja.sj的更新答案不工作,但是,图这个指令将减少魔法串在我的code。

Update @codeninja.sj's updated answer does work, however, figure this directive will cut down on magic strings in my code.

这篇关于AngularJS不会绑定到选择列表中的数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆