gpt4 book ai didi

javascript - 使用 ng-repeat 添加多个 View 实例时的范围问题

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

在使用 AngularJS 的 ng-repeat 功能时,我遇到了范围界定问题。

请参阅plnkr

我有一个对象数组“boxCollection”和一个项目列表“itemCollection”,它们显示在下拉列表中。

   $scope.boxCollection = [];

$scope.itemCollection =
[
{name: 'item1'},
{name: 'item2'},
{name: 'item3'}
];

现在我的观点是

<script type="text/ng-template" id="addBox.html">
<div class="box-controls">
<span class="glyphicon glyphicon-plus pull-left" ng-click="addBox()"></span>
<span class="glyphicon glyphicon-minus pull-left" ng-class="{disable_div:boxCollection.length < 2} " ng-click="removeBox($index)"></span>
</div>

<div class="box-container">
<div class="box-details">

<div class="boxItem">
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-3">Item</label>
<div class="col-md-8">
<select class="form-control" ng-options="item.name for item in itemCollection" ng-model="boxCollection[$index].item" ng-disabled="false">
<option value=""> None </option>
</select>
</div>
</div>

<div class=" form-group ">
<label class="control-label col-md-3">Item Desc</label>
<div class="col-md-8">
<input type="text " class="form-control " ng-model="boxCollection[$index].item.desc ">
</div>
</div>
</form>
</div>

</div>
<div class="clearfix "></div>
</div>
</script>

该 View 包装在带有 id 的脚本标记中,并使用 ng-repeat 进行调用。

我有一个函数可以将框元素添加到我的 View “addBox()”中。它在“boxCollection”数组中生成一个条目,在“boxTmplList”数组中生成另一个条目。 'boxTmplList' 负责显示 View 。

现在,如果您从 box1 的下拉列表中选择“item1”并在输入字段中添加一个值,请使用“+”按钮在 View 中添加另一个框,然后在另一个实例中再次选择“item1”。它在输入字段 2 中显示输入字段 1 的值。

enter image description here

经过进一步分析,我发现 Angular 使用相同的 $hashkey 来跟踪具有相似“item”名称的对象。

我正在使用一种解决方法,将另一个属性添加到对象“boxCollection[$index].itemDesc”而不是“boxCollection[$index].item.desc”,然后使用另一个函数修改该对象,但是我觉得这不是最有效的方法。

对此的任何见解将不胜感激。

最佳答案

您需要将 ng-model="boxCollection[$index].item" 更改为 ng-model="boxCollection[$index].item.name" ,就像-

<select class="form-control" ng-options="item.name for item in itemCollection" ng-model="boxCollection[$index].item.name" ng-disabled="false">

关于javascript - 使用 ng-repeat 添加多个 View 实例时的范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36275710/

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