代码之家  ›  专栏  ›  技术社区  ›  xtofl Adam Rosenfield

angular.js分层模型:孙辈不工作

  •  0
  • xtofl Adam Rosenfield  · 技术社区  · 11 年前

    我想了解一下Angular。特别是,我想创建一个分层数据结构,可以使用分层视图进行操作:

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

    (实际代码位于 http://jsfiddle.net/xtofl/n3jqM/12 )

    此刻,我试着停在两个层次上,即根有孩子和孙子。

    孙辈的“移除”按钮会触发 child.remove(grandchild) 作用但是,删除元素不会导致删除行:(

    我不明白为什么。除此之外,小提琴的例子似乎一下子增加了4个孙子。

    相关代码:

    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;
    };
    

    相关的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>
    

    问题:这有什么错 makeChild 函数 ng-click="addChild()" 呼叫添加4 li 元素,并且 ng-click="child.removeChild(grandchild)" 不会导致孙辈被免职吗?

    1 回复  |  直到 11 年前
        1
  •  2
  •   Stepan Suvorov bolelamx    11 年前

    你的问题不在AngularJS中

    这是Array.prototype.remove的错误

    应该是

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

    更新的fdl- http://jsfiddle.net/STEVER/n3jqM/13/

    更新日期:

    而不是

        ret.children = makeChild(nextIndex++);
    

    你应该这样做

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

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

    享受;)