使用 AngularJS,假设数组 $scope.data.children
具有以下结构的项目:
{
"sku" : "<sku>",
"selected" : <boolean>,
"children" : []
}
是否有一种简单的方法来引用所有 selected = true
子项,最好在 $scope.data.components
中表示?
例如,如果
[
{"sku" : "A","selected" : true, "children":[
{"sku" : "A1","selected" : true, "children":[]},
{"sku" : "A2","selected" : false, "children":[]}
]},
{"sku" : "B","selected" : false, "children":[
{"sku" : "B1","selected" : false, "children":[]},
{"sku" : "B2","selected" : false, "children":[]}
]},
{"sku" : "C","selected" : true, "children":[
{"sku" : "C1","selected" : true, "children":[]},
{"sku" : "C2","selected" : false, "children":[]}
]},
{"sku" : "D","selected" : false, "children":[
{"sku" : "D1","selected" : false, "children":[]},
{"sku" : "D2","selected" : false, "children":[]}
]}
]
然后
$scope.data.components = [
{"sku" : "A","selected" : true, "children":[
{"sku" : "A1","selected" : true, "children":[]},
},
{"sku" : "C","selected" : true, "children":[
{"sku" : "C1","selected" : true, "children":[]}
}
]
如果$scope.data.children
更新为[{"sku": "D","selected": true}]
然后$scope.data.components =
[
{"sku" : "A","selected" : true, "children":[
{"sku" : "A1","selected" : true, "children":[]},
},
{"sku" : "C","selected" : true, "children":[
{"sku" : "C1","selected" : true, "children":[]}
},
{"sku" : "D","selected" : true, "children":[
{"sku" : "D2","selected" : true, "children":[]}
}
]
总结要求:
- 实时 View - 对
$scope.data.children
或$scope.data.components
的更改应立即反射(reflect)在两者上。 - 任何深度的
children
元素都应该检查selected == true
- 一旦检测到错误,就不应检查任何子子项。
- (可选,但如果可能的话很好)任何对
组件
的引用都只会显示selected == true
的children
。因此,如果对"sku":"A"
对象的引用在node
上可用,则node.components
将返回node.children
其中"sku":"A"
的子级select == true
最佳答案
根据您给定的示例 json,我尝试了在 angularjs 中使用 forEach 的一种实现
我只是循环遍历子数组并在需要时构造组件数组
angular.forEach($scope.children, function(child) {
var grandChildValue = 0; //value to check for component node already exist
angular.forEach(child.children, function(grandChild) {
if(grandChild.selected) {
if(grandChildValue != 0) {
// if node already exist means it will be added to children from here
angular.forEach($scope.components, function(comp){
if(comp.sku == child.sku) {
comp.children.push(grandChild);
}
});
return;
}
//if node doesn't exist, it will create the node in component array & children inserted
grandChildValue++;
$scope.components.push({
"sku" : child.sku,
"selected": child.selected,
"children":[grandChild]
});
}
});
});
这是一个包含您的代码的工作插件,
http://embed.plnkr.co/Yv6BaLQQY03TMsnv0yHk/preview
希望这有帮助!
关于javascript - 自动为数据提供不同的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30352382/