我有2个独立的json对象来自服务器。下面的Json A是Car model对象,在查看汽车时可以获取。 Json B是元数据,当网页首次加载时,它会在整个应用程序中使用。
我需要做的是在wheel_id
上对wheel_handlers
进行查找,然后从json B返回轮对象,然后我可以在视图中使用它并打印结果。我想我需要用ng-repeat做一些事情,但我不确定是否诚实。
A - 汽车模型
[{
id: 14,
name: "Audi",
wheel_handlers: [
{
id: 9,
wheel_id: 62,
arguments: {
amount: 10
}
}
]
}]
B - 轮
{
id: 62,
name: "Change Wheel Size",
arguments: [
{
id: 25,
description: "amount"
}
]
}
答案 0 :(得分:2)
我假设如下:Json“A”可能包括几个汽车,还有几个wheel_handlers(因为wheel_handler
处有一个数组)。因此,汽车的JSON也可能如下所示:
[
{
id: 14,
name: "Audi",
wheel_handlers: [
{
id: 9,
wheel_id: 62,
arguments: {
amount: 10
}
},
{
id: 12,
wheel_id: 65,
arguments: {
amount: 12
}
},
{
id: 15,
wheel_id: 30,
arguments: {
amount: 8
}
}
]
},
{
id: 16,
name: "Mercedes",
wheel_handlers: [
{
id: 9,
wheel_id: 62,
arguments: {
amount: 10
}
},
{
id: 12,
wheel_id: 65,
arguments: {
amount: 12
}
}
]
}
]
对于JSON文件B,我假设您还意味着一个可能包含多个轮定义的数组。举个例子:
[
{
id: 62,
name: "Change Wheel Size",
arguments: [
{
id: 25,
description: "amount"
}
]
},
{
id: 65,
name: "test wheel",
arguments: [
{
id: 25,
description: "amount"
}
]
},
{
id: 30,
name: "another wheel",
arguments: [
{
id: 25,
description: "amount"
}
]
}
]
如果是这种情况,您可以迭代汽车,同时迭代调用AngularJS控制器中的辅助函数。您可以调用此辅助函数并将当前汽车的wheel_handlers
作为参数。然后,此辅助函数检查每个wheel_id
条目的wheel_handler
,并在JSON b文件中搜索这些ID - 轮定义。辅助函数返回一个包含轮子的数组,因此在视图中您可以迭代轮子。这将使用嵌套的ng-repeat
,因为首先你迭代汽车,然后迭代汽车,你将迭代车轮。
以下是控制器部分的示例。我使用$scope.cars
作为JSON A,$scope.wheels
作为JSON B。
var testApp = angular.module('testApp', []);
testApp.controller('testContr', function ($scope) {
$scope.cars = [];
$scope.wheels = [];
$scope.getWheelsByIds = function (wheel_handlers) {
var wheelIds = [];
var returnArray = [];
for (var wheelKey in wheel_handlers) {
wheelIds.push(wheel_handlers[wheelKey].wheel_id);
}
for (var key in $scope.wheels) {
console.log(wheelIds.indexOf($scope.wheels[key].id));
if (wheelIds.indexOf($scope.wheels[key].id) > -1) {
returnArray.push($scope.wheels[key]);
}
}
return returnArray;
}
});
必要的HTML部分可能如下所示:
<div ng-app="testApp" ng-controller="testContr">
<div ng-repeat="car in cars" ng-init="wheels = getWheelsByIds(car.wheel_handlers)">
<span>Car name: {{car.name}}</span><br/>
<div ng-repeat="wheel in wheels">
<span>Wheel name: {{wheel.name}}</span><br/>
</div>
<br/>
<br/>
</div>
</div>
我使用测试数据创建了一个小提琴演示,请在此处查看:http://jsfiddle.net/4F3YD/10/
答案 1 :(得分:0)
您可以在这里使用角度滤镜。在过滤器函数中,您可以在第二个json中检查id。
更多Documentation on Angular Filter
代码示例:
<div ng-repeat="element in wheel | filterIds:element.id">
并过滤功能:
.filter('filterIds', function () {
return function(id) {
$scope.carModel.forEach(function(car){
if(id == car.id)
return id;
});
}
})
答案 2 :(得分:0)
你可以像这样嵌套ng-repeats,虽然我不确定你想要实现什么
下面的代码将重复通过汽车,然后车轮和车轮和显示轮子从车轮ID(车轮)匹配,希望这是有道理的
<div ng-repeat="car in CarModels">
<div ng-repeat="wheel in car.wheel_handlers">
{{Wheels | filter:wheel.wheel_id}}
</div>
</div>