Question

I'm trying to get to know Angular a bit. In particular, I want to create a hierarchical data structure, that can be manipulated using a hierarchical view:

Root:
  - addChild
  - child 1: { remove, addChild, child1, child2, ...}
  - child 2: { remove, addChild, child1, child2, ...}
  ....

(real code at http://jsfiddle.net/xtofl/n3jqM/12)

At the moment I try to stop at 2 levels, i.e. the Root has children and grandchildren.

The grandchildren's 'remove' button does trigger the child.remove(grandchild) function. However, the removal of the element does not result in rows being removed :(

I don't manage to understand why. On top of that, the example at the fiddle seems to add 4 grandchildren at once.

The relevant code:

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:

    <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 is so wrong about this makeChild function that an ng-click="addChild()" call adds 4 li elements at once, and that the ng-click="child.removeChild(grandchild)" does not result in grandchildren to be removed?

Was it helpful?

Solution

you problem is not in AngularJS

it was mistake with Array.prototype.remove

it should be

Array.prototype.remove = function (element) {
    var index = this.indexOf(element);
    this.splice(index,1 );
};

updated fdl - http://jsfiddle.net/STEVER/n3jqM/13/

UPD:

and instead of

    ret.children = makeChild(nextIndex++);

you should do

    ret.children.push(makeChild(nextIndex++));

http://jsfiddle.net/STEVER/n3jqM/14/

enjoy ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top