我可能只是在抚摸,但我在使用下面的一小段代码时遇到了麻烦。我已经嵌套了ng-repeats和ng-includes,并希望从任意级别的嵌套中删除一个项目。 SOOO ...
<div ng-repeat="item in List" ng-include="'item.html'">
</div>
item.html
<div>
<h1>{{ item.title }}</h1>
<div ng-repeat="item in item.List" ng-include="'item.html'"></div>
<button ng-click="removeItem(item)">Remove me!</button>
</div>
显然,如果我可以访问父级List
数组,我可以根据索引拼接出来,但我对如何访问该父对象有严重的大脑迷雾。知道如何将父母与item
一起传递给ng-include? p>
答案 0 :(得分:0)
我知道如何将父项与项目一起传递给ng-include? p>
我认为将父级传递给子级会导致代码复杂性和难以维护。我还说,当我们谈论大数据时,它会对性能产生影响。您不使用带有隔离范围的嵌套指令,因此我将使用其他方法根据唯一值a.e。从嵌套树中删除节点:
function removeFromTree(parent, childNameToRemove){
console.log(parent);
parent.nodes = parent.nodes.filter(function(child){
return child.name !== childNameToRemove;
}).map(function(child){
return removeFromTree(child, childNameToRemove);
});
return parent;
}
$scope.removeItem = function(item){
$scope.displayTree[0] = removeFromTree( $scope.displayTree[0], item.name);
}
的 Demo plunker 强>
HTML 的
<div ng-controller="DialogDemoCtrl">
<div class="span5 article-tree">
<div ng-style="{'overflow': 'auto'}">
<script type="text/ng-template" id="tree_item_renderer">
<span>
{{showNode(data)}}
</span>
<button ng-click="removeItem(data)">Remove me!</button>
<li ng-repeat="data in data.nodes" class="parent_li" ng-include="'tree_item_renderer'" tree-node></li>
</ul>
</script>
<div class="tree well">
<ul>
<li ng-repeat="data in displayTree" ng-include="'tree_item_renderer'"></li>
</ul>
</div>
</div>
</div>
</div>
JS
angular.module('plunker', ['ui.bootstrap'])
.controller('DialogDemoCtrl', function ($scope, $http) {
buildEmptyTree();
function removeFromTree(parent, childNameToRemove){
console.log(parent);
parent.nodes = parent.nodes.filter(function(child){
return child.name !== childNameToRemove;
}).map(function(child){
return removeFromTree(child, childNameToRemove);
});
return parent;
}
$scope.removeItem = function(item){
$scope.displayTree[0] = removeFromTree( $scope.displayTree[0], item.name);
}
function buildEmptyTree() {
$scope.displayTree =
[{
"name": "Root",
"type_name": "Node",
"show": true,
"nodes": [{
"name": "Loose",
"group_name": "Node-1",
"show": true,
"nodes": [{
"name": "Node-1-1",
"device_name": "Node-1-1",
"show": true,
"nodes": []
}, {
"name": "Node-1-2",
"device_name": "Node-1-2",
"show": true,
"nodes": []
}, {
"name": "Node-1-3",
"device_name": "Node-1-3",
"show": true,
"nodes": []
}]
}, {
"name": "God",
"group_name": "Node-2",
"show": true,
"nodes": [{
"name": "Vadar",
"device_name": "Node-2-1",
"show": true,
"nodes": []
}]
}, {
"name": "Borg",
"group_name": "Node-3",
"show": true,
"nodes": []
}, {
"name": "Fess",
"group_name": "Node-4",
"show": true,
"nodes": []
}]
}];
[{
"name": "Android",
"type_name": "Android",
"icon": "icon-android icon-3",
"show": true,
"nodes": []
}];
}
});