javascript - angular.js 分层模型 : grandchildren not working

标签 javascript angularjs data-binding hierarchical-data

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

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

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

目前我尝试停在 2 个级别,即根有子代和孙子。

孙子的“删除”按钮确实会触发 child.remove(grandchild) 函数。但是,删除元素不会导致行被删除:(

我不明白为什么。最重要的是, fiddle 上的例子似乎同时添加了 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)" 不会导致孙子被删除?

最佳答案

你的问题不在 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/

享受;)

关于javascript - angular.js 分层模型 : grandchildren not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21647683/

相关文章:

wpf - 如何将 XmlDataProvider.Source 绑定(bind)到 MVVM 属性

Javascript - 无法动态添加 onmouseover

javascript - 如果值重复,为什么 AngularJS 不想列出数组项?

javascript - AngularJS:一个 'partial form' 用于创建和更新文章

java - Android 数据绑定(bind)错误 :Execution failed java. lang.RuntimeException:

c# - gridview 将下拉列表绑定(bind)到 List<keyvaluePair<int, string>>

javascript - 为什么用 execCommand 证明不能正常工作?

javascript - Async.js - ETIMEDOUT 和回调已被调用

javascript - 找不到模块内的 AngularJS 服务

javascript - 用knockoutjs组织单页网站html代码