我的代码就像这样
<body>
<div ng-app=''>
<div ng-controller="questionCtrl">
<div>
<ul />
<li ng-repeat="prdElement in palletElement">
<input type="text" ng-model="prdElement.name" placeholder="Name" required />
<ul>
<li ng-repeat="elemnt in prdElement.children">
<div>
<span>
<input type="text" ng-model="elemnt.name" placeholder="Name" required />
</span>
<span ng-hide="elemnt.length == 1">
<a href ng-click="prdElement.splice($index, 1)">remove</a>
</span>
</div>
<hr />
</li>
<li>
<a href ng-click="newPrdItem($event)">New Item</a>
</li>
</ul>
</li>
</div>
<div>
<button ng-click="showitems($event)">Submit</button>
</div>
<div id="displayitems" style="visibility:hidden;">
{{prdElement}}
</div>
</div>
</div>
function questionCtrl($scope){
var counter=0;
$scope.palletElement = [{
name: 'Pallet 1',
children: [{
name: '11',
}, {
name: '12',
}]
}, {
name: 'Pallet 2',
children: [{
name: '21'
}, {
name: '22'
}]
}]
$scope.newPrdItem = function ($event) {
counter++;
$scope.prdElement.children.push({ id: counter, name: ''});
$event.preventDefault();
}
$scope.showitems = function($event){
$('#displayitems').css('visibility','none');
}
}
JSFiddle 所有看起来都没问题,但添加和删除元素功能不起作用
答案 0 :(得分:1)
你有一个$scope.palletElement
,它是一个包含两个位置的数组,并且具有children
属性,但是在$scope.newPrdItem
函数中,您正在访问children
元素数组(不存在)而不是访问第一个或第二个数组位置中对象的children
属性,因此这有效:
$scope.prdElement[0].children.push({ id: counter, name: ''});
$scope.prdElement[1].children.push({ id: counter, name: ''});
而不是:
$scope.prdElement.children.push({ id: counter, name: ''});
执行此操作的一种可能方法是更改$scope.newPrdItem
函数以传递添加了新子元素的prdElement
。
另一个问题出在你的删除功能中,在这种情况下你犯了类似的错误,在这种情况下你将splice
应用于对象而不是数组,所以使用:
prdElement.children.splice($index, 1)
而不是:
prdElement.splice($index, 1)
您的代码中的所有内容如下所示:
function questionCtrl($scope){
var counter=0;
$scope.palletElement = [{
name: 'Pallet 1',
children: [{
name: '11',
}, {
name: '12',
}]
}, {
name: 'Pallet 2',
children: [{
name: '21'
}, {
name: '22'
}]
}]
$scope.newPrdItem = function (prdElement, $event) {
counter++;
prdElement.children.push({ id: counter, name: '', inline: true });
$event.preventDefault();
}
$scope.showitems = function($event){
$('#displayitems').css('visibility','none');
}
}
<body>
<div ng-app=''>
<div ng-controller="questionCtrl">
<div>
<ul />
<li ng-repeat="prdElement in palletElement">
<input type="text" ng-model="prdElement.name" placeholder="Name" required />
<ul>
<li ng-repeat="elemnt in prdElement.children">
<div>
<span>
<input type="text" ng-model="elemnt.name" placeholder="Name" required />
</span>
<span ng-hide="elemnt.length == 1">
<a href ng-click="prdElement.children.splice($index, 1)">remove</a>
</span>
</div>
<hr />
</li>
<li>
<a href ng-click="newPrdItem(prdElement,$event)">New Item</a>
</li>
</ul>
</li>
</div>
<div>
<button ng-click="showitems($event)">Submit</button>
</div>
<div id="displayitems" style="visibility:hidden;">
{{prdElement}}
</div>
</div>
</div>
</body>
希望这有帮助,