我正在尝试了解一下 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/