Javascript AngularJS:如何将JSON字符串解析为整数或浮点以在表单数字字段中显示它
我的前端使用AngularJS,后端使用Laravel。我正在向前端屏幕传递一个名为Javascript AngularJS:如何将JSON字符串解析为整数或浮点以在表单数字字段中显示它,javascript,arrays,json,angularjs,laravel,Javascript,Arrays,Json,Angularjs,Laravel,我的前端使用AngularJS,后端使用Laravel。我正在向前端屏幕传递一个名为orderItems的变量,该变量包含以下数据 [{ "item_description": "CAD Machine ", "qty": "1", "unit_price": "4000.00" }, { "item_description": "Lenovo laptop", "qty": "1", "unit_price": "3000.00" }] 我的前
orderItems
的变量,该变量包含以下数据
[{
"item_description": "CAD Machine ",
"qty": "1",
"unit_price": "4000.00"
}, {
"item_description": "Lenovo laptop",
"qty": "1",
"unit_price": "3000.00"
}]
我的前端包含一个文本字段和两个数字字段。文本字段中正在填充数据,数字字段中未显示任何数据
以下是我在视图中的代码:
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Description</th>
<th>Quantity</th>
<th>Cost</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in order.items">
<td>
{{ Form::text("description[]",null, ['ng-model' => 'item.item_description', 'class' => 'input-small form-control', 'placeholder' => 'Item description', 'required']) }}
</td>
<td>
{{ Form::number("quantity[]", null, ['step' => 'any', 'ng-model' => 'item.qty', 'class' => 'input-mini form-control', 'placeholder' => 'Qty']) }}
</td>
<td>
{{ Form::number("cost[]", null, ['step' => 'any', 'ng-model' => 'item.unit_price', 'class' => 'input-mini form-control', 'placeholder' => 'Unit Price', 'required']) }}
</td>
<td>
<h4><% item.qty * item.cost | currency %></h4>
</td>
<td class="text-center">
<h5><a href ng-click="removeItem($index)"><i class="fa fa-times"></i> Remove</a></h5>
</td>
</tr>
</tbody>
</table>
由于我的知识有限,我不知道如何将
数量
和单价
解析为浮点/整数。在这种情况下,您不需要解析它们
通常,Javascript是解释的,因此在大多数浏览器中,如果您执行以下操作:
"3.5"*"2"
它会起作用的。
但是,如果出于某些原因需要强制解析,可以使用:
parseFloat
parseInt
在
这两个函数分别解析字符串和返回解析后的值
这两项是最可靠的功能。还有其他可能性,例如:
+ before the number (such as +"3.5")
Integer.parseInt(myNumber)
但是这些并不是每个浏览器都能识别的@wayne感谢您的建议,我通过在model类上设置Quantity和unit\u price的访问器来更改服务器响应
public function getQtyAttribute($value)
{
return $this->attributes['qty'] = (float)$value;
}
public function getUnitPriceAttribute($value)
{
return $this->attributes['unit_price'] = (float)$value;
}
这是json中的链接,数字应该是float/int而不是string?最好在服务器上更改它。这是一个选项吗?谢谢,我会尝试在服务器响应中进行更改。谢谢您的回复。但是,如何在表单input type=number中显示值?
+ before the number (such as +"3.5")
Integer.parseInt(myNumber)
public function getQtyAttribute($value)
{
return $this->attributes['qty'] = (float)$value;
}
public function getUnitPriceAttribute($value)
{
return $this->attributes['unit_price'] = (float)$value;
}