/*factory method for getting particular customers order*/
factory.getCustomer = function(customerId) {
for(var i=0,len=customers.length ; i<len ; i++) {
if(customers[i].id === parseInt(customerId)){
return customer[i];
}
}
return {};
};
return factory();
/*Controller*/
myApp.controller('OrdersController',['$scope','$routeParams','customersFactory', function($scope,$routeParams,customersFactory) {
var customerId = $routeParams.customerId;
$scope.customer = null;
function init() {
$scope.customer = customersFactory.getCustomer(customerId);
}
init();
}]);
/*View*/
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>{{customer.name}}'s Orders</h2>
<table class="table table-hover">
<tr>
<th>Product</th>
<th>Total</th>
</tr>
<tr ng-repeat="order in customer.orders">
<td>{{ order.product }}</td>
<td>{{ order.total | currency }}</td>
</tr>
</table>
</div>
</div>
</div>
/*JSON FILE*/
{
"id": "1",
"joined": "2000-12-2",
"name": "Wali",
"city": "Dubai",
"orderTotal": "9.0765",
"orders": [
{
"id": "1",
"product": "protein",
"total": "11.987"
}
]
},
{
"id": "2",
"joined": "2004-12-2",
"name": "Ali",
"city": "London",
"orderTotal": "20.0765",
"orders": [
{
"id": "2",
"product": "bcca",
"total": "2.3456"
},
{
"id": "3",
"product": "baseball",
"total": "4.3456"
}
]
},
{
"id": "3",
"joined": "1980-11-2",
"name": "Zen",
"city": "Australia",
"orderTotal": "6.500",
"orders": [
{
"id": "3",
"product": "chocolate",
"total": "6.4567"
}
]
}
我已经制作了客户表格,我们可以从中执行 CRUD 功能,但当我点击查看特定客户订单时,它会将我重定向到正确的视图通过路由,但特定客户的订单没有显示。
任何人都可以为此提出解决方案吗?
答案 0 :(得分:0)
根据您的JSON数据,ID是 String ,但您将其解析为整数,并使用===,仅当值和时才匹配strong>比较变量的类型匹配。
您需要更改if语句,其中一个选项是:
if (parseInt(customers[i].id) === parseInt(customerId))
另一种选择是:
if (customers[i].id == customerId)
另一种选择是使用angular的$ filter服务。 您需要将它注入工厂,而不是为了获得客户端,您可以使用:
var customer = $filter('filter')(customers, {id: customerId.toString()}, true);
return customer.length === 1 ? customer[0] : null;
toString 部分仅仅是因为您的JSON数据具有ID作为字符串,并且第三个参数设置为true以防止“like”过滤器(默认$ filter行为将返回id 10,例如如果customerId是1)。