AngularJS数字输入和默认值

3
我遇到了一个有关AngularJS和数字输入的怪问题。默认值会在页面加载后短暂出现,但之后就会消失。我已在Firefox和Chrome浏览器上测试过。
从服务器返回的数据如下:
{
    "name":"Rodolfo Heller",
    "desc":"Et ullam autem iure. Facere non fuga sit. Dolorum reprehenderit voluptatem vero rem at in.",
    "sell":"44.44",
    "image":"xxxx",
    "id":"1",
    "quantity":"1"
}

我在数字输入框中也有一个ng-init="product.quantity=1",但数字1会闪一下然后消失。

<input type='number' min="1" step="1" class='form-control' ng-model="product.quantity" ng-init="product.quantity=1">

有什么想法,为什么默认值会消失?
谢谢。

你的 JSON 中没有逗号。这是真实服务器返回的结果,还是在 POST 请求中出现了错误? - Karim BENHDECH
啊,抱歉这是从Chrome开发工具复制粘贴的。现在已经修复了。 - James Elliott
如果您在模板中添加{{product.quantity}},会发生同样的事情吗? - Karim BENHDECH
不,那个数字是可见的。 - James Elliott
你能否创建一个 jsfiddle,因为一切似乎都很好。在这里测试过了 链接 - Bardh Lohaj
1个回答

4
可能是由于从服务器返回的数据类型有问题。
{
    desc: "Et ullam autem iure. Facere non fuga sit. Dolorum reprehenderit voluptatem vero rem at in."
    id: "1"
    image: "hidden"
    name: "Rodolfo Heller"
    quantity: "1"                   // String value for quantity
    sell: "44.44"
}

您需要将quantity赋值给一个number输入框,但是服务器会以string的形式发送quantity。如果您将数据类型从服务器端进行int类型的强制转换,或者将number输入框更改为text类型,则可以解决问题。

因此,如果您选择使用int类型,则数据应该如下所示:

{
    desc: "Et ullam autem iure. Facere non fuga sit. Dolorum reprehenderit voluptatem vero rem at in."
    id: "1"
    image: "hidden"
    name: "Rodolfo Heller"
    quantity: 1                   // int
    sell: "44.44"
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接