Currently, I am delving into the world of Angular and exploring its functionalities. My main goal is to construct a hierarchical data structure that can be easily manipulated using a hierarchical view:
Root:
- addChild
- child 1: { remove, addChild, child1, child2, ...}
- child 2: { remove, addChild, child1, child2, ...}
....
(actual code available at http://jsfiddle.net/xtofl/n3jqM/12)
Presently, my aim is to create a structure with 2 levels only, where the Root has children and grandchildren.
When clicking on the 'remove' button for grandchildren, it triggers the child.remove(grandchild)
function. However, the removal does not result in the corresponding rows being removed :(
I'm struggling to comprehend the reason behind this issue. Additionally, in the provided fiddle example, it seems to add 4 grandchildren simultaneously.
The key parts of the code are as follows:
function Controller($scope) {
$scope.nextChildIndex = 1;
$scope.addChild = function () {
$scope.children.push(makeChild($scope.nextChildIndex++));
};
$scope.removeChild = function (child) {
$scope.children.remove(child);
};
$scope.children = [];
}
var makeChild = function (i) {
var nextIndex = 1;
var ret = {
index: i,
children: []
};
ret.addChild = function () {
ret.children = makeChild(nextIndex++);
};
ret.removeChild = function (child) {
ret.children.remove(child);
};
return ret;
};
The relevant html snippet:
<ul ng-repeat="grandchild in child.children">
<li class="grandchild">
<button ng-click="child.removeChild(grandchild)">-grandchild</button>
<span>child {{grandchild.index}}</span>
</li>
</ul>
Question: What could be causing the unexpected behavior with the makeChild
function that results in multiple li
elements being added when ng-click="addChild()"
is triggered? Moreover, why does
ng-click="child.removeChild(grandchild)"
fail to remove the grandchildren?