gpt4 book ai didi

html - 在angularjs中使用ng-repeat动态添加div

转载 作者:行者123 更新时间:2023-11-28 05:17:17 25 4
gpt4 key购买 nike

我是 angularjs 的初学者。我想在单击添加图标时动态添加一个 div。我已经为此做了一些脚本。

HTML 部分:

<div ng-show="child" class="childDiv" data-ng-repeat="choice in choices track by $index">
<label for="childname" class="childname" >ServerName </label>
<input ng-model="serverinfo.childname" type="text" required="required" placeholder="name"/>
<label for="childname" class="childname" >Fullname</label>
<input ng-model="serverinfo.childfullname" type="text" required="required" placeholder="fullname"/>
<label for="childname" class="childname" >Mandatory Field</label>
<input ng-model="serverinfo.field" type="text" required="required" placeholder="city/county.."/>
<label for="childname" class="childname" >Field values</label>
<input ng-model="serverinfo.value" type="text" required="required" placeholder=""/>
<i ng-click="removechild()" ng-show="$last" style="padding-left:16em;" class="material-icons">remove</i>
</div>
<i ng-click="addchild()" style="padding-left:16em;" class="material-icons">add</i>

JS部分:

$scope.addchild  = function() {
// $scope.child = true;
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};

$scope.removechild = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};

我的输出是这样的,enter image description here

我的问题是,无论我在文本框中输入什么,它都会自动复制到下一组。任何人都可以弄清楚这个问题。

最佳答案

您当前将所有值绑定(bind)到同一个对象 serverinfo,并且因为您在一个循环 (ng-repeat) 中,所以循环中的每个字段绑定(bind)到 Controller 中的同一对象。

你有两个选择:

将字段绑定(bind)到 choice 元素:

<div ng-show="child" class="childDiv" data-ng-repeat="choice in choices track by $index">
<input ng-model="choice.childname" type="text" required="required" placeholder="name"/>
</div>

以上将属性直接绑定(bind)到每个选择,并将通过 console.log( $scope.choices[0].childname );

在 Controller 中可用

使用 $index 指标创建一个匹配选项数组:

当您不想覆盖/更改原始数组的值时,这是一个很好的解决方案。

<div ng-show="child" class="childDiv" data-ng-repeat="choice in choices track by $index" ng-init="serverinfo[ $index ].id = choice.id">
<input ng-model="serverinfo[ $index ].childname" type="text" required="required" placeholder="name"/>
</div>

上面将属性绑定(bind)到一个新的数组对象名称serverinfo,其中每个元素都与$scope.choices中的一个选项相关,它将在 Controller 通过 console.log( $scope.serverinfo[0].childname );

请注意,我还添加了 ng-init="serverinfo[ $index ].id = choice.id" 以将每个选择的 id 属性复制到新的由 ngRepeat 指令循环动态创建的数组元素。

关于html - 在angularjs中使用ng-repeat动态添加div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43609770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com