【发布时间】:2014-04-29 20:30:34
【问题描述】:
我正在使用具有结构的嵌套数组...
$scope.items = [{attr1: val1,
attr2: val2,
items: [{
attr1: val1,
attr2: val2,
items: [{
...
}, ...]
}, ...]
}, ...];
像这样进入ng-repeat 和ng-include
<div ng-repeat="item in items" ng-include="'/path/to/template.tpl.html'"></div>
而template.tpl.html 是
<div>{{item.attr1}}<\div>
<div>{{item.attr2}}<\div>
<div ng-click="fnAddNewItemBelow(item, $parent)"><\div>
<div ng-repeat="item in item.items" ng-include="'/path/to/template.tpl.html'"><\div>
现在,在控制器中,我通常想做一些事情,比如
- 查找项目的父项
- 查找项目的同级
- 计算兄弟姐妹数
- 找出一个项目嵌套了多少层
- 在嵌套的任何级别插入或删除项目
但我不确定如何优雅地做到这一点。例如,想象一下我想实现fnAddNewItemBelow。我可以解决的两个选项是
遍历作用域
使用 Angular 提供的嵌套范围结构
// pseudo-code only
$scope.fnAddNewItemBelow = function (item, parent) {
var newItem = ...;
// add newItem as a sibling after the item that was ng-clicked
// parent.$parent is necessary because the ng-include adds another scope layer (I think)
parent.$parent.item.items.push(newItem);
// (probably need to use .splice in case there are items after item,
// but I'm keeping it simple)
}
但这很丑陋,因为它对结构的假设太多(如果我将 ng-if 放在 <div ng-click... 上,这增加了另一个范围级别......那么我需要parent.$parent.$parent.item.items.push(newItem))。
递归迭代嵌套数组,直到找到 item.id
另一种方法是直接在$scope.items 上操作,因为 Angular 会更新 UI 和与之关联的范围。我可以使用 for 循环通过 $scope.items 递归迭代,并在通过它拥有的某个唯一 ID 定位项目后,在其后插入 newItem
// pseudo-code only
$scope.fnAddNewItemBelow = function (item) {
var newItem = ...;
// add newItem as a sibling after the item that was ng-clicked
fnSomeFunctionToFindItemAndInsertItemAfterIt(item.id, newItem);
}
fnSomeFunctionToFindItemAndInsertItemAfterIt (itemId, newItem) {
// fancy recursive function that for loops through each item, and calls
// itself when there are children items. When it finds item with itemId, it
// splices in the newItem after
}
我不喜欢这样,因为每次我想对嵌套数组做某事时,它都需要遍历整个项目树。
还有更优雅的解决方案吗?
【问题讨论】:
标签: angularjs angularjs-ng-repeat